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

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

问题描述

已经通读了这个相关问题,但正在寻找更具体的内容.

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

  • 有没有办法明确告诉编译器您希望枚举的宽度?
  • 如果是这样,你是怎么做的?我知道如何在 C# 中指定它;在 C 中是否类似?
  • 这是否值得做?当枚举值传递给函数时,它会作为 int 大小的值传递吗?
  • 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?

一般情况下没有.不在标准 C 中.

In general case no. Not in standard C.

这是否值得做?

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

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?

如今,许多(大多数)编译器将所有参数作为给定硬件平台的自然字长值传递.例如,在 64 位平台上,许多编译器会将所有参数作为 64 位值传递,而不管它们的实际大小,即使类型 int 在该平台上有 32 位(因此,它在这样的平台上通常不会作为整型"值传递).出于这个原因,为了参数传递的目的而尝试优化枚举大小是没有意义的.

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天全站免登陆