1

How come ANSI C allows extraneous code before any case labels within a switch statement?

#include <stdio.h>

int main(void) {
  const int foo = 1;

  switch (foo) {
      printf("wut\n"); /* no label, doesn't output */
    case 1:
      printf("1\n");
      break;
    default:
      printf("other\n");
      break;
  }

  return 0;
}

compiled with

$ gcc -pedantic -Wall -Werror -Wextra -ansi test.c

It compiles without warnings and executes fine - sans "wut".

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145

1 Answers1

1

It is allowed to put statements in switch without any label. Standard says about that:

C11: 6.8.4.2 The switch statement (p7):

In the artificial program fragment

switch (expr)
{
    int i = 4;
    f(i);
    case 0:
        i = 17;
        /* falls through into default code */
    default:
         printf("%d\n", i);
}

the object whose identifier is i exists with automatic storage duration (within the block) but is never initialized, and thus if the controlling expression has a nonzero value, the call to the printf function will access an indeterminate value. Similarly, the call to the function f cannot be reached.

haccks
  • 104,019
  • 25
  • 176
  • 264