在以下位置找到此代码C 谜题 http://www.gowrikumar.com/c/index.php:
#include<stdio.h>
int main()
{
int a=1;
switch(a)
{ int b=20;
case 1: printf("b is %d\n",b);
break;
default:printf("b is %d\n",b);
break;
}
return 0;
}
Output:
b is 51
我似乎无法理解这个输出。
You're using a variable with an indeterminate value (invoking undefined behaviour) by jumping past the initialization of the variable b
. The program can produce any value and it will be correct.
C 标准甚至涵盖了这种情况(在非规范示例中)。
ISO/IEC 9899:2011 §6.8.4.2switch
陈述:
7 示例在人工程序片段中
switch (expr)
{
int i = 4;
f(i);
case 0:
i = 17;
/* falls through into default code */
default:
printf("%d\n", i);
}
其标识符为的对象i
存在并具有自动存储持续时间(在块内),但永远不会
初始化,因此如果控制表达式具有非零值,则对 printf 函数的调用将
访问不确定的值。同样,调用该函数f
无法连接。
请注意“不确定值”注释。
There is some room for discussion about whether accessing an indeterminate value leads to undefined behaviour. Under some circumstances (trap representations), it can lead to undefined behaviour. It will take me some time to determine whether 'possibly undefined behaviour' should be considered 'undefined behaviour'. Accessing an uninitialized variable is a bad idea, and there is nothing you can say about the value that is printed in your code.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)