枚举长度的数组大小给出编译错误

Array size of enum length gives compilation error

看看下面的代码,

此代码编译正常:

enum ids {
    X,
    Y,
    NUM_IDS,
}

void some_func(void)
{
    static char* const names[NUM_IDS] = { "name X" , "name Y"};
}

但是这段代码无法编译: 错误:'names' 的存储大小不是常量

enum ids {
    X,
    Y,
    NUM_IDS,
}

void some_func(void)
{
    int nr_names = NUM_IDS;
    static char* const names[nr_names] = { "name X" , "name Y"};
}

我想我误解了常量表达式的意思。是否以第二种方式成为 C90 中不存在的 VLA?有人请澄清。

static char* const names[nr_names] 是 VLA,因为 nr_names 不是常量表达式,而是(非常量)int。当然,在这个简短的示例中,它始终等于 NUM_IDS,但您仍然不能这样做。


在不相关的旁注中,建议将 char 定义为 const,因为修改它不会起作用,因为它是程序二进制文件的一部分(在 C++ 中它不会'不要让你有它非常量):

static const char* const names[NUM_IDS] = { "name X" , "name Y" };

问题是 VLA 不允许有静态存储持续时间

引用自 ISO 9899 6.7.5.2 数组声明符

If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type.

因此,一般情况下不允许声明静态 VLA。因为 nr_names 不是常量,所以不允许在第二个代码中使用 static。

第一个代码是正确的,因为NUM_IDS是常量表达式。

您的第二个代码的其他问题是无法初始化 VLA。

我引用 ISO 9899 6.7.8 初始化

The type of the entity to be initialized shall be an array of unknown size or an object type that is not a variable length array type