C标准中可变修改类型的switch语句约束说明 [英] Explanation of switch statement constraints on variably modified types in C standard
问题描述
我正在编写一个 C 编译器,当我谈到 switch
语句的实现时,一个约束让我很困惑.标准的第 6.8.4.2p2 节状态:
I'm writing a C compiler, and when I come to the implementation of the switch
statement one constraint confused me a lot. Section 6.8.4.2p2 of the standard states:
如果 switch 语句在其中包含关联的 case 或默认标签具有可变修改类型的标识符的范围,整个switch 语句应在该标识符的范围内.
If a switch statement has an associated case or default label within the scope of an identifier with a variably modified type, the entire switch statement shall be within the scope of that identifier.
带脚注:
也就是说,声明要么在 switch 语句之前,要么在 switch 语句之前遵循与该开关关联的最后一种情况或默认标签在包含声明的块中.
That is, the declaration either precedes the switch statement, or it follows the last case or default label associated with the switch that is in the block containing the declaration.
我真的不明白这个约束是什么意思.谁能给我一个例子?
I can't really understand what this constraint means. Can some one give me an example?
推荐答案
这就是说,如果一个case能够看到一个可变修改的数组,那么整个switch
语句必须也能看到它.
What this is saying is that if one case is able to see a variably modified array, then the entire switch
statement MUST be able to see it as well.
这意味着下面的代码是合法的:
This means that the following code is legal:
void switch_test(int size)
{
int array[size];
...
// code to populate array
...
switch (expr) {
case 1:
printf("%d
", array[0]);
break;
case 2:
// do something else
}
}
但这段代码不是:
void switch_test(int size)
{
switch (expr) {
case 2:
// do something else
int array[size]; // ILLEGAL, VLA in scope of one label but not all
case 1:
...
// code to populate array
...
printf("%d
", array[0]);
}
}
后者是非法的原因是因为如果代码要跳转到案例 1,那么 array
可能没有正确创建,因为 VLA 的大小是在运行时确定的.确保 VLA 在 switch
语句之前可见可以避免此问题.
The reason the latter is illegal is because if the code were to jump to case 1 then array
might not have been created properly since the size of a VLA is determined at run time. Ensuring that the VLA is visible before the switch
statement avoids this issue.
这篇关于C标准中可变修改类型的switch语句约束说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!