cswitch-statementonline-compilation

Difference in C compilers


As per the link C Switch-case curly braces after every case , the below code should not compile since the variable is declared within switch without braces.

        case 2:
    
            int s = 0;
            printf("enter side value:");
            scanf("%d", &s);

            printf("area of square is %d", squarearea(s));
        break;

However lot of online c editors ( https://www.onlinegdb.com/online_c_compiler , https://www.programiz.com/c-programming/online-compiler/ ) are allowing this program to compile and run .

Why is it so ? These online compilers are claiming to use gcc but then why is this difference in behavior?


Solution

  • Testing with Compiler Explorer suggests GCC changed in version 11 to accept labeled declarations, which is an extension to the current C standard language.

    In the OnlineGDB compiler you link to, adding the extra switch -pedantic produces a warning message, confirming that the compiler is treating this as an extension to the language but knows it is not part of the C standard.

    GCC documents this: “ISO C2X allows labels to be placed before declarations and at the end of a compound statement. As an extension, GNU C also allows all this in C90 mode.” (“ISO C2X” means the upcoming ISO C standard, likely to be C 2023.)