C中的变量定义忽略 [英] Variable Definition Ignore in C

查看:22
本文介绍了C中的变量定义忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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;
}

输出:它为 b 打印一些垃圾值b 的声明何时发生在这里为什么这里 b 没有用 20 初始化???

Output: It prints some garbage value for b when does the declaration of b takes place here Why b is not initialized with 20 here???

推荐答案

因为内存会分配给 int b 但是当应用程序运行时 "b = 20"永远不会被评估.

Because memory will be allocated for int b but when the application is run "b = 20" will never be evaluated.

这是因为您的 switch 语句将跳转到 case 1:1default:, 跳过有问题的语句 - 因此 b 将未初始化并调用未定义的行为.

This is because your switch-statement will jump down to either case 1:1 or default:, skipping the statement in question - thus b will be uninitialized and undefined behavior is invoked.

以下两个问题(以及他们接受的答案)将进一步帮助您寻找答案:

The following two questions (with their accepted answers) will be of even further aid in your quest searching for answers:

为什么不能变量在 switch 语句中声明?

将编译器警告/错误提高到更高级别有望在您尝试编译源代码时为您提供此信息.

Turning your compiler warnings/errors to a higher level will hopefully provide you with this information when trying to compile your source.

以下是gcc 对此事的说明;

Below is what gcc says about the matter;

foo.cpp:6:10: error: jump to case label [-fpermissive]
foo.cpp:5:9: error:   crosses initialization of 'int b'

<小时>

1 因为 int a 永远是 1(一)所以它永远跳到这里.


1 since int a will always be 1 (one) it will always jump here.

2 两个链接中最相关的,由我回答.

2 most relevant out of the two links, answered by me.

这篇关于C中的变量定义忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆