Issue with switch statement

邮差的信 提交于 2020-12-04 01:42:53

问题


Let's see the problem by code:

code-1

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a =1;
    switch (a)
    {
        printf("This will never print\n");
    case 1: 
        printf(" 1");
        break;
    default:
        break;
    }   
    return 0;
}

Here the printf() statement is never going to execute - see http://codepad.org/PA1quYX3. But

code-2

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

Here int b is going to be declared - see http://codepad.org/4E9Zuz1e.

I am not getting why in code1 printf() doesn't execute but in code2 int b is going to execute.

Why?

Edit: i got that int b; is declaration and it is allocate memory at compile time so whether control flow reach there or not that declaration will be done.

Now see this code

#include<stdio.h>

int main()
{
   if(1)
   {
    int a; 
   }

a =1;
return 0;
}

here int a is in control flow path still yet this not going to compile...why?


回答1:


Think of switch as just a goto with labels. It doesn't matter where you goto, as long as a variable declaration is above where you use it, you can use it. This is partially due to the fact that a variable declaration is not an executable statement that gets "done" like an expression. That switch is very nearly equivalent to:

int a  = 1;

{
    if (a == 1) goto case1;
    goto defaultcase;

    int b;

case1:
    b = 34;
    printf("%d", b);
    goto end;

defaultcase:
    goto end;

end:
}

return 0;

And the gotos have nothing to do with the scope of b.

Try doing this though:

switch (a)
{
int b = 1;
....

In that case, even though b is declared, the initialisation will be skipped because that is an executable statement that can either be done or not done. Your compiler should warn you if you try to do that.

Regarding the declaration inside if (updated question): In that case, a has a scope limited to the if. It is created when the scope is entered, and is destroyed when the scope ends.




回答2:


Because int b; is a declaration and the compiler will not generate code for it.

int a = 1;

switch (a) {

/* Instructions corresponding to the code here will not be executed */
/* printf("hi"); Instructions for such code will never be executed */
/* int b;      It is just a declaration. No executable code is generated for it*/

int b = 34;/*Replaced int b by int b = 34 now b will never be initialized to 34*/
case 1:
   printf("%d",b);      /*you will get garbage value now*/
   break;
default:
   break;
}


来源:https://stackoverflow.com/questions/8557261/issue-with-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!