Valid, but worthless syntax in switch-case?

后端 未结 8 1424
爱一瞬间的悲伤
爱一瞬间的悲伤 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.

    0 讨论(0)
  • 2021-01-30 04:24

    It is possible to implement a "loop and a half" with it, although it might not be the best way to do it:

    char password[100];
    switch(0) do
    {
      printf("Invalid password, try again.\n");
    default:
      read_password(password, sizeof(password));
    } while (!is_valid_password(password));
    
    0 讨论(0)
提交回复
热议问题