gpt4 book ai didi

c - switch 语句中的变量定义

转载 作者:太空狗 更新时间:2023-10-29 16:37:55 25 4
gpt4 key购买 nike

在下面的代码中,为什么变量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 groupedinto one syntactic unit. The initializers of objects that haveautomatic storage duration, and the variable length array declaratorsof ordinary identifiers with block scope, are evaluated and the valuesare stored in the objects (including storing an indeterminate valuein objects without an initializer) each time the declaration isreached in the order of execution, as if it were a statement, andwithin 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 thestatement that is the switch body, depending on the value of acontrolling expression, and on the presence of a default label and thevalues of any case labels on or in the switch body. A case or defaultlabel is accessible only within the closest enclosing switchstatement.

因此,变量 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 withautomatic storage duration (within the block) but is neverinitialized, and thus if the controlling expression has a nonzerovalue, the call to the printf function will access an indeterminatevalue. Similarly, the call to the function f cannot be reached.

关于c - switch 语句中的变量定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com