Question:
Why doesn't this compile?
#include <stdio.h>
int main(void) {
int valor = 0;
scanf("%d", &valor);
switch (valor) {
case 0:
int variavel = 1;
printf("%d", variavel);
break;
default:
int variavel = 2;
printf("%d", variavel);
}
}
Answer:
A very common mistake is for people to think that the case
is a command block and generates a new scope. Actually the case
is just a label . So it's just a name for an address of the code used to trigger a diversion. In fact a switch
is just a goto
based on a value.
This already works:
#include <stdio.h>
int main(void) {
int valor = 0;
scanf("%d", &valor);
switch (valor) {
case 0: {
int variavel = 1;
printf("%d", variavel);
break;
} default: {
int variavel = 2;
printf("%d", variavel);
}
}
}
See working on ideone . And on repl.it. Also posted on GitHub for future reference .
The braces create a block and a scope, then you can create variables.