Why can not you declare a variable within a case?

11

Why does not 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);
    }
}
    
asked by anonymous 09.01.2017 / 16:02

1 answer

12

A common misconception is that people find that case is a block of commands and generates a new scope. In fact% w / o% is just a label . So it's just a name for a code address used to cause a deviation. In fact a case is only a switch 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 running on ideone .

The keys create a block and a scope, there you can create the variables.

    
09.01.2017 / 16:02