在C中指定枚举类型的大小 [英] Specifying size of enum type in C

查看:180
本文介绍了在C中指定枚举类型的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经通过这个相关的问题阅读,但正在寻找更具体的一些东西。




  • 有没有办法告诉你的编译器你想要你的枚举有多宽?

  • 如果是这样,怎么办你做吧?我知道如何在C#中指定它在C中也是这样吗?

  • 这甚至值得吗?当枚举值被传递给一个函数时,它会作为一个 int 的值被传递吗?

$ b $有没有办法告诉你的编译器
具体你想要你的
枚举是多大? ?


一般情况下不。



这取决于上下文。如果你正在谈论将参数传递给函数,那么不,这不值得(见下文)。如果是在从枚举类型构建聚合时节省内存,那么可能值得做。但是,在C中,您可以简单地在聚合中使用适当大小的整数类型而不是枚举类型。在C(与C ++相反)中,枚举类型和整数类型几乎总是可互换的。


当枚举值传递给一个函数时,将会作为一个大小的值被传递,而不管?


这些天很多(大多数)编译器将所有参数作为自然字的值给定硬件平台的大小。例如,在64位平台上,许多编译器将以64位值的形式传递所有参数,无论其实际大小如何,即使类型为 int 在其中有32位那个平台(所以在这样一个平台上它通常不会被传递为int)。因此,尝试优化参数传递用途的枚举大小没有任何意义。


Already read through this related question, but was looking for something a little more specific.

  • Is there a way to tell your compiler specifically how wide you want your enum to be?
  • If so, how do you do it? I know how to specify it in C#; is it similarly done in C?
  • Would it even be worth doing? When the enum value is passed to a function, will it be passed as an int-sized value regardless?

解决方案

Is there a way to tell your compiler specifically how wide you want your enum to be?

In general case no. Not in standard C.

Would it even be worth doing?

It depends on the context. If you are talking about passing parameters to functions, then no, it is not worth doing (see below). If it is about saving memory when building aggregates from enum types, then it might be worth doing. However, in C you can simply use a suitably-sized integer type instead of enum type in aggregates. In C (as opposed to C++) enum types and integer types are almost always interchangeable.

When the enum value is passed to a function, will it be passed as an int-sized value regardless?

Many (most) compilers these days pass all parameters as values of natural word size for the given hardware platform. For example, on a 64-bit platform many compilers will pass all parameters as 64-bit values, regardless of their actual size, even if type int has 32 bits in it on that platform (so, it is not generally passed as "int-sized" value on such a platform). For this reason, it makes no sense to try to optimize enum sizes for parameter passing purposes.

这篇关于在C中指定枚举类型的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆