This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

switch case fail

void xx(char cc)
{ char aa; switch(cc) { case 1:case 0: aa=1; break; case 2,3: aa=2; break; }
}

//----------------------------------

xx(0); //run OK
xx(1); //run OK
xx(2); //run FAIL <<*****************
xx(3); //run OK

Parents Reply Children
  • The comma is probably one of the more misunderstood operators in C.

    And because of what it does, the compiler will silently accept code that does something completely different from what the user may think.

    But in this case, I'm a bit surprised. I didn't think C would allow a comma expression in a case statement.

    The language standard says that the keyword "case" takes a constant expression.

    And that a constant expression "shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not
    evaluated."

    So I would have expected a compilation error and not a problem at runtime, since the comma operator is explicitly mentioned as not allowed.

  • 0 Error(s) 0 warning(s) ,you can step test

  • No need to step test. It doesn't matter if the compiler should have accepted that expression or not. The source code is incorrect. And you can't expect correct behaviour if the source code is incorrect.

  • 0 Error(s) 0 warning(s) ,you can step test
    I know of no C compiler that catches and report each and every possible mistake.

    Erik