Is it possible to declare a variable inside switch case ?

The answer Yes and No. Yes, We can declare a variable inside a switch case and No, We cannot declare a variable inside a switch case.

Confusing :( !! Why Yes and Why No?

We will see the answer with the help of the following program

Example:

#include <stdio.h>
int main()
{
    int a;
    switch (a)
    {
        case 1:
        {
            int x;
        }
        break;
        case 2:
            int y;
        break;
    }
    return 0;
}

This program will give the following Error

error: a label can only be part of a statement and a declaration is not a statement

If you look at the program, compiler did not give any error for int x declaration, but it gives the above error for the int y declaration.


Why is it? 

int x is declared within the  braces ({}) but int y is not like that. The scope of any variable should be within the {} (not applicable for local variable). If We declare a variable within a switch case without braces compiler cannot assign the scope of that variable, that is why the above error is shown.