In C, an array normally isn't allowed to have size 0 (unless I use the one or other compiler-side extension).
在C中,通常不允许数组具有0大小(除非使用一个或其他编译器端扩展)。
OTOH, there are VLAs whose length might turn out to be 0.
OTOH,有VLAs其长度可能是0。
Are they allowed?
他们允许吗?
I am talking about the following code:
我说的是以下代码:
void send_stuff()
{
char data[4 * !!flag1 + 2 * !!flag2];
uint8_t cursor = 0;
if (flag1) {
// fill 4 bytes of data into &data[cursor]
cursor += 4;
}
if (flag2) {
// fill 2 bytes of data into &data[cursor]
cursor += 2;
}
}
The result is a data
array with a length of 0, 2, 4 or 6, depending on the combination of the flags.
结果是一个长度为0、2、4或6的数据数组,具体取决于标记的组合。
The question is now: Is this valid code for the case the array turns out to have length 0?
现在的问题是:对于数组的长度为0的情况,这个有效代码是否有效?
1 个解决方案
#1
9
This is not valid, if we go to the draft C99 standard section 6.7.5.2
Array declarators paragraph 5 says (emphasis mine):
这是无效的,如果我们看C99标准章节6.7.5.2数组声明者第5段说(强调我的):
if the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero.[...]
如果size是一个非整数常量表达式的表达式:如果它出现在函数原型作用域中的声明中,则将其视为被*替换;否则,每次评估时,它的值都应该大于0。
In fact with clang
enabling the sanitizer for undefined behavior using the -fsanitize=undefined
flag can generate a run-time warning for this case see it live:
事实上,通过使用-fsanitize=未定义的标志,clang可以为未定义的行为启用消毒剂,可以为这个案例生成一个运行时警告:
runtime error: variable length array bound evaluates to non-positive value 0
运行时错误:变量长度数组绑定的值为0
#1
9
This is not valid, if we go to the draft C99 standard section 6.7.5.2
Array declarators paragraph 5 says (emphasis mine):
这是无效的,如果我们看C99标准章节6.7.5.2数组声明者第5段说(强调我的):
if the size is an expression that is not an integer constant expression: if it occurs in a declaration at function prototype scope, it is treated as if it were replaced by *; otherwise, each time it is evaluated it shall have a value greater than zero.[...]
如果size是一个非整数常量表达式的表达式:如果它出现在函数原型作用域中的声明中,则将其视为被*替换;否则,每次评估时,它的值都应该大于0。
In fact with clang
enabling the sanitizer for undefined behavior using the -fsanitize=undefined
flag can generate a run-time warning for this case see it live:
事实上,通过使用-fsanitize=未定义的标志,clang可以为未定义的行为启用消毒剂,可以为这个案例生成一个运行时警告:
runtime error: variable length array bound evaluates to non-positive value 0
运行时错误:变量长度数组绑定的值为0