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?
Think of
switchas just agotowith labels. It doesn’t matter where yougoto, 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:And the
gotos have nothing to do with the scope ofb.Try doing this though:
In that case, even though
bis 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,ahas a scope limited to theif. It is created when the scope is entered, and is destroyed when the scope ends.