c++ - C/C++ 中的大小写标签问题

标签 c++ c label case

我遇到了这段代码

  #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 fcannot be reached.

关于c++ - C/C++ 中的大小写标签问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5762465/

相关文章:

c++ - 可变参数函数在编译时接受相同类型的参数并对其进行迭代

c++ - "C"和 "extern C"之间的权限差异

c++ - 类似模板参数的函数

c - 说C是用C编译的是什么意思?

java - 中断和标签, "The label MyLabel is missing"

three.js - 在 3D 对象上方附加文本

C++:无法在使用条件类型的模板函数中使用类型为 'char*' 的左值初始化类型为 'double' 的参数

C头文件包含错误

c - 是否可以访问 "recursive mode"中的指针?

python - matplotlib 标签中的下标文本