Why can’t you declare a variable within a case?

Asked

Viewed 1,550 times

12

Why don’t you 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);
    }
}

1 answer

13


A very common mistake is for people to think that the case is a command block and generates a new scope. Actually case is just one label. So it’s just a name for an address of the code used to cause a deviation. Actually a switch is just one 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);
    }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.