What does comma operator mean in a switch statement?

后端 未结 6 405
-上瘾入骨i
-上瘾入骨i 2021-01-17 07:31

I was given a question and was asked to give the output.

int main(void){  
    int x = 2;  
    switch(x){  
        case 1,2,1: printf(\"Case 1 is executed\         


        
6条回答
  •  礼貌的吻别
    2021-01-17 08:02

    is it a compiler error or not.

    The code is invalid in both languages: the case expression must be a constant expression, and a constant expression can't contain a comma operator. (In C, this is stated explicitly; in C++, you have to unpick the grammar to find that a constant-expression must be a conditional-expression, which can't contain a comma).

    Even if you were allowed to use the comma operator here, the switch statement would still be invalid since two cases would both have the same value, 1.

    And if not why does the code run only on turbo C.

    Because both languages have changed significantly since that prehistoric compiler was last updated. Don't use it if you want to learn variants of C or C++ from this century.

提交回复
热议问题