我遇到了这段代码
#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;
}
我预计输出为 20,但得到了一些垃圾值。 将此代码编译为.c 文件和.cpp 文件时,输出会有所不同吗?
最佳答案
在 C++ 中,代码格式错误,因为跳转到 case 1
会跨越 b
的初始化。你不能那样做。
在 C 中,代码调用 UB 因为使用了未初始化的变量 b
。
C99 [6.4.2/7] 也有类似的例子。
EXAMPLE In the artificial program fragment
switch (expr) { int i = 4; f(i); case 0: i = 17; /* falls through into defaultcode */ 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++ - C/C++ 中的大小写标签问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762465/