-1

I faced with new for me C/C++ switch/if/else/case syntax. I can't find it's mention in C standart. Value inside "if" doesn't matter, "if(1)" or "if(0)" works same. Seems this "if" doesn't act like condition, but as scope. Is it compiler extension or compiler sugar ?

#include <stdio.h>

int main()
{
    int a = 0, b = -1, c = -1;
    switch(a)
    {
        if(1) { 
            case 0: b = 0;
            printf("%u:b=%d\n", __LINE__, b);
        }
        else if(0) {
            case 1: b = 1; 
            printf("%u:b=%d\n", __LINE__, b);
        }
        else if(0) {
            case 2: b = 2; 
            printf("%u:b=%d\n", __LINE__, b);
        }
        else {
            case 3: b = 3; 
            printf("%u:b=%d\n", __LINE__, b);
        }
        c = 0;
        printf("%u:b=%d, c=%d\n", __LINE__, b, c);
        break;
    }

    printf("b=%d", b);
    return 0;
}
  • What do you expect to happen here with these if statements? – JVApen Oct 26 '20 at 12:58
  • In the future, please tag a question with just one language, C or C++, unless it involves some difference or interaction between them. Answers may be different in different languages, so they should be addressed in different questions. – Eric Postpischil Oct 26 '20 at 13:00
  • I added C and C++, because I tested with C and C++ compilers – Vadim Ostanin Oct 26 '20 at 13:16

1 Answers1

2

A switch jumps to the selected case label. The if conditions are never evaluated because program control never flows to them. This is specified by the C standard and C++ standards.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Is this some elaborate workaround to avoid using `break`? It seems to have the same effect (+ extra warnings) – Yksisarvinen Oct 26 '20 at 13:02
  • Maybe. I saw such approach at https://github.com/jmacd/xdelta, and it makes me curious – Vadim Ostanin Oct 26 '20 at 13:23
  • 1
    @Yksisarvinen: It gives a control flow that differs from break: After the specific case code is executed, control flows out of the chained if-else statement to the statements that follow it but are still within the switch statement, whereas a break would exit the switch. This also differs from putting those statements after the switch since they are executed only if some case matches (not if no case matches). However, the code is quite ugly and obtuse, so it seems unworthwile. – Eric Postpischil Oct 26 '20 at 13:36