2

In C, you can define a variable at the beginning of any block.

For example, the following is correct (although setting i to 5 is weird):

    int i = 5;

    for (i=0; i<1; i++) {
        int j = 1;
        printf("Value FOR: %d\n", j);

    }

Strangely, when doing this in a switch, the value of j seems random.

    int i = 5;

    switch (i)
    {
        int j = 1;
    default:
        printf("Value SWITCH: %d\n", j);
        break;
    }

The piece of code above prints the following on my machine: Value SWITCH: 8 (while it should be Value SWITCH: 1)

Any idea why?

Could it be because in default block, it is actually not instantiated and it reads in random memory?

FYI: I am using gcc version 4.6.1 on Windows, if that matters.

Jean-Francois T.
  • 11,549
  • 7
  • 68
  • 107
  • I think, that he jumps immediately to the default so, thats why, because he always jump to the labels! Maybe this can help you understand: https://stackoverflow.com/questions/35866193/variable-definition-inside-switch-statement – Gonçalo Bastos Dec 02 '20 at 08:48
  • This can help you :https://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement – MED LDN Dec 02 '20 at 09:52

0 Answers0