C / C ++ in the switch / case trap

Source: http://www.cnblogs.com/dolphin0520/

On the C / C ++ in the switch / case trap

  Look at the following piece of code:

  Main.cpp file

Copy the code
#include<iostream>
using namespace std;


int main(int argc, char *argv[])
{
    int a =0;
    switch(a)
    {
        case 0: int b=1;cout<<b<<endl;break;
        case 1: cout<<b<<endl;break;
        default:break;
    }
    return 0;
}
Copy the code

  Compiled under gcc compiler results:

  Tip skip the initialization process variable b. For a local variable, where it has its scope as defined in it until the end of the block of statements, then for variable B, it is a block of statements in the minimum switch {} block, then it is said that after case 0 section, variable b is visible (Note before case 0 variable b is not accessible). Consider a case where, when a value of 1, the program execution jumps to case 1, case b while accessible, but skip its initialization process. And if the definition of a variable is initialized at the same time, indicating that the programmer wants to initialize the variable, but this time skip the variable is initialized, it could lead to unexpected program programmer can not occur, so the compiler to skip in order to avoid such initialization and cause unpredictable result, the statement error.

  If the above code to:

 switch(a)
    {
        case 0: int b;b=0;cout<<b<<endl;break;
        case 1: cout<<b<<endl;break;
        default: break;
    }

  Compiled results:

  Just be warned, because there is no definition of variables are initialized at the time, that is how the implementation of the program will not skip the initialization process variable, not to say the process is skipped and cause unpredictable errors or program crashes . So just be warned.

  Look at the following code:

 switch(a)
    {
        case 0: break;
        default: int b=1;cout<<b<<endl;break;
    }

  这段代码没有报错。因为如果执行case 0,变量b没有进行初始化,但是由于在case 0部分b是不可见的,因此不会对程序造成任何影响,而如果执行default分支,则b会被初始化,因此程序没有报错。

  归根到底,出现上述的crosses initialization和jump to case label错误的原因是由于变量的作用域问题,因此一个好的习惯就是在case子句下面加上大括号来限定变量的作用域。

 switch(a)
    {
        case 0: {int b=1;cout<<b<<endl;break;}
        case 1: break;
        default: break;
    }

  不过要注意,一旦加上了大括号,在case 0后面便不能访问到变量b了。

  注意,如果上述代码以C方式进行编译,编译结果则会有所不同:

  main.c

Copy the code
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
    int a =2;
    switch(a)
    {
        
        case 0: int b=17;printf("%d\n",b);break;
        case 1: break;
        default:printf("%d\n",b);break;
    }
    return 0;
}
Copy the code

  编译结果:

 

   报的错误意思是在该标签下不能定义变量。为什么呢?原因很简单,在C语言中所有的变量定义都必须放到所在语句块的最前面。所以如果改成这样:

Copy the code
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
    int a =2;
    switch(a)
    {
        int b=17;
        case 0: printf("%d\n",b);break;
        case 1: break;
        default:printf("%d\n",b);break;
    }
    return 0;
}
Copy the code

  编译结果:

  No error, note that there are no reported crosses initialization error, this is a little different from C and C ++. If the C ++ compiler way, certainly will be reported crosses initialization errors, which further indicates that more stringent requirements than C ++ C in Grammar.

  The program running results:

  Output 32, is a random value. Since b is not initialized, the output is a random value.

  Other supplements:

Consult internal switch variable definition of the problem?

#include <iostream>
using namespace std;

int main()
{
    bool b = false;

    switch (false)
    {
        case true:
            int ival;
            break;

        case false:
            ival = 3;
            cout << ival << endl;
    }

    return 0;
}

This c ++ code should be executed directly case false switch statement, so ival should not be defined, why the program can compile and execute successfully? (Compiler gcc4.7)
here ival should be local variables, stack the allocation of space ah, then there should be no problem in a good space has been allocated at compile time it should run?
Answer:

ival is a local variable scope within the braces are located.

So the second case still belong to the scope of the variable.

In addition, variable definitions are not statements, it is not necessary to perform the full range is also effective. Here, although the first case statement is not executed, but it's still valid variable definitions.

Variable initialization can be skipped rather than variable definitions. Variables are valid regardless of where the definition, switch can only skip variable is initialized variable definition can not skip.


I asked the Lord had misunderstood the role and definition of variables declared in the static field, and whether to perform does not matter. Define the variable does not exist to perform the action.

Why is this easily misunderstood, because the comparative tragedy c language switch statement design, each case is not part of an independent scope. To understand it, one way is to see it as a goto. For example, this program is:



Author: know almost Users
link: https: //www.zhihu.com/question/23051685/answer/23463267
Source: know almost
copyrighted by the author. Commercial reprint please contact the author authorized, non-commercial reprint please indicate the source.



Published 18 original articles · won praise 86 · views 160 000 +

Guess you like

Origin blog.csdn.net/u013178472/article/details/73521518