2
#include<stdio.h>
 int main()
{
     switch(2)
    {
            case 1:
                    if(1)
                    {
                            case 2:
                                    printf("hello\n");
                    };
    }
    return 0;
}

OUTPUT = hello as I'm passing 2 in switch case 1 is not true then also it enters it and executes code inside case 2. How come it enters case 1? Thanks.

nrussell
  • 18,382
  • 4
  • 47
  • 60
ayuj
  • 29
  • 1
  • FWIW, `switch(2)` does not make a lot of sense either. You usually switch on the value of a variable. AFAICT, it does not enter `case 1:`, it jumps to `case 2:` directly. And `if(1)` is useless too. – Rudy Velthuis Sep 20 '14 at 15:22
  • Have a look here http://stackoverflow.com/questions/5569416/how-can-duffs-device-code-be-compiled – phuclv Sep 20 '14 at 18:29

2 Answers2

2

After switch(2), it will jump immediately to the case 2 label. The fact that it is within an if block contained within case 1 is irrelevant. case 2: effectively functions no differently from a goto label, so it will jump to it wherever it is. It is not true that case 1 is somehow being entered.

To clarify, properly indented it looks thus:

#include<stdio.h>
int main() {
  switch(2) {
  case 1:
    if(1) {
  case 2:
      printf("hello\n");
    }
    ;
  }
  return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Crowman
  • 25,242
  • 5
  • 48
  • 56
0

how come it enters case 1 ?

It doesn't enter the case 1. In fact if(1) has no use here. The above code is equivalent to

#include<stdio.h>
int main()
{
    switch(2)
    {
        case 1:
        case 2: printf("hello\n");
    }
    return 0;
}  

To see the irrelevant use of if you can replace if(1) with if(0) and you will find that result will be the same.

haccks
  • 104,019
  • 25
  • 176
  • 264
  • through its o/p i also know that its similar 2 what u say but , my question is how ? – ayuj Oct 30 '14 at 10:58