在下面的代码中,为什么变量i
没有赋值1
?
#include <stdio.h>
int main(void)
{
int val = 0;
switch (val) {
int i = 1; //i is defined here
case 0:
printf("value: %d\n", i);
break;
default:
printf("value: %d\n", i);
break;
}
return 0;
}
当我编译时,我收到一条关于 i
没有被初始化的警告,尽管 int i = 1;
清楚地初始化了它
$ gcc -Wall test.c
warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
printf("value %d\n", i);
^
如果val = 0
,则输出为0
。
如果 val = 1
或其他任何值,则输出也为 0。
请向我解释为什么变量 i
在开关中被声明但没有被定义。标识符为 i
的对象具有自动存储持续时间(在 block 内)但从未初始化。为什么?
最佳答案
根据C标准(6.8语句和 block ),强调我的:
3 A block allows a set of declarations and statements to be grouped into one syntactic unit. The initializers of objects that have automatic storage duration, and the variable length array declarators of ordinary identifiers with block scope, are evaluated and the values are stored in the objects (including storing an indeterminate value in objects without an initializer) each time the declaration is reached in the order of execution, as if it were a statement, and within each declaration in the order that declarators appear.
和(6.8.4.2 switch语句)
4 A switch statement causes control to jump to, into, or past the statement that is the switch body, depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch body. A case or default label is accessible only within the closest enclosing switch statement.
因此,变量 i
的初始值设定项永远不会被求值,因为声明
switch (val) {
int i = 1; //i is defined here
//...
由于跳转到案例标签而未达到执行顺序,并且与任何具有自动存储持续时间的变量一样具有不确定的值。
另请参阅 6.8.4.2/7 中的规范示例:
EXAMPLE In the artificial program fragment
switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into default code */ default: printf("%d\n", i); }
the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.
关于c - switch 语句中的变量定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866193/