Variable Definition Ignore in C

This question already has an answer here:

  • Variable definition inside switch statement 5 answers

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

    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:

  • How can a variable be used when it's definition is bypassed? 2

  • Why can't variables be declared in a switch statement?


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

    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 since int a will always be 1 (one) it will always jump here.

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


    Switch statements only evaluate portions of the code inside them, and you can't put code at the top and expect it to get evaluated by every case component. You need to put the b initialization higher in the program above the switch statement. If you really need to do it locally, do it in a separate set of braces:

    Code:

    int main()  
    {
      int a=1;
      /* other stuff */
      {
        int b=20;
        switch(a)
        {
    
          case 1:
          printf("b is %dn",b);
          break;
    
          default:
          printf("b is %dn",b);
          break;
        }
      }
      /* other stuff... */
      return 0;
    }
    

    switch直接跳转到case 1: :,从不执行任务。

    链接地址: http://www.djcxy.com/p/84446.html

    上一篇: 为什么x86上的整数溢出会导致无限循环?

    下一篇: 在C中忽略变量定义