Why we can not define a variable twice in switch? [duplicate]

Because the scope is delimited by { and } and you have the a variable twice.

You can avoid this compilation error by:

switch(x) {
    case 1: {
        int a = 1;
        break;
    }
    case 2: {
       int a = 2;
       break;
    }
}

Note that in your example the compiler fails to succeed, because if you remove the first break statement, а something that is called fall-through might happen:

All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

In this case the statements that are going to be executed (because of the fall-through), are :

  1. int a = 1;
  2. int a = 1;
  3. break;

And as you can see, the a variable is duplicated, which is why the compiling fails in your example.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)