我想知道是否可以通过将枚举放在结构中来限制枚举的访问方式。我知道这会在 C++ 中工作(这就是我的想法),但我不知道它是否会在 c 中工作。因此,例如,如果我有两个不同的结构
struct SaticArrayA
{
enum { MAX_SIZE = 10 };
int array[MAX_SIZE];
};
struct SaticArrayB
{
enum { MAX_SIZE = 20 };
int array[MAX_SIZE];
};
这甚至会关闭编译吗?基本上,我想做我在 C++ 中会做的事情,并给自己一个跨“类”的通用命名约定,这样我就可以询问任何数组的大小,等等。
(p.s. 我基本上是想在 c 中给自己一个更好的静态数组,它不会在我尝试将它传递给另一个范围时丢失大小信息(通过衰减到指针))。
最佳答案
它不会编译,
你没有给枚举器一个标签
enum { MAX_SIZE = 10 } name ;
并且你声明了两个同名的枚举常量
MAX_SIZE
关于标识符范围的 C11 标准:
6.2.1. p7 Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator
这意味着您的第一个枚举器在整个文件中都有一个范围,从它声明的行开始。
第二个同名枚举声明不正确,不应编译。
无论在何处为该规则声明枚举都无关紧要,无论是否为结构,一旦声明它们从那时起就在文件范围内。
关于如果在 c 中的结构内定义,枚举的范围是否有限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547474/