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

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

问题描述

已通过阅读此相关的问题,但一直在寻找一些更具体一点。


  • 有没有办法明确告诉你的编译器你想要多宽的枚举是什么?

  • 如果是这样,你怎么办呢?我知道如何在C#中明确指定。它是类似于用C做了什么?

  • 难道甚至是值得做的事情?当枚举值传递给一个函数,将它作为一个 INT -sized值传递不管?


解决方案

  

有没有办法告诉你的编译器
  具体如何广泛您希望您的
  枚举是什么?


在一般情况下,不。不是标准C


  

难道甚至是值得做?


这取决于上下文。如果你谈论的是传递函数的参数,则没有,这是不值得做的(见下文)。如果它是关于节能建筑从枚举类型聚集的时候内存,那么它可能是值得做的事情。然而,在C你可以简单地使用适当大小的整数类型而不是枚举类型的聚集。在C(而不是C ++)枚举类型和整数类型几乎都是可以互换的。


  

在枚举值传递给一个函数,将其作为考虑一个int大小的值传递?


许多(大多数)编译器这些天传递的所有参数的给定的硬件平台的自然字大小的值。例如,在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天全站免登陆