Valid, but worthless syntax in switch-case?

后端 未结 8 1422
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-30 03:38

Through a little typo, I accidentally found this construct:

int main(void) {
    char foo = \'c\';

    switch(foo)
    {
        printf(\"Cant Touch This\\n\");         


        
8条回答
  •  走了就别回头了
    2021-01-30 04:17

    Does this serve any purpose at all?

    Yes. If instead of a statement, you put a declaration before the first label, this can make perfect sense:

    switch (a) {
      int i;
    case 0:
      i = f(); g(); h(i);
      break;
    case 1:
      i = g(); f(); h(i);
      break;
    }
    

    The rules for declarations and statements are shared for blocks in general, so it's the same rule that allows that that also allows statements there.


    Worth mentioning as well is also that if the first statement is a loop construct, case labels may appear in the loop body:

    switch (i) {
      for (;;) {
        f();
      case 1:
        g();
      case 2:
        if (h()) break;
      }
    }
    

    Please don't write code like this if there is a more readable way of writing it, but it's perfectly valid, and the f() call is reachable.

提交回复
热议问题