How is this switch statement evaluated?

How does the compiler interpret this switch statement? I am assuming the content is inside the switch statement (41), so why does it go to case 2?

    int i = 4;
    int j = 2;

    switch(i++-j) {         //switch is evaluted to be (41)??
    case 3: i++; break;
    case 1: j++; break;
    case 2: j+=2; break;
    case 5: i+=2; break;
    default: i +=5; break;
    }

    System.out.println(i);  //Prints out 4
    System.out.println(j);  //Prints out 5

      

+3


source to share


3 answers


Break it down:

i++-j

      

++

has a higher precedence than -

, so this:

(i++)-j

      



++

is the postfix increment - it will evaluate the value i

before incrementing. The initial value i

is 4, so:

4-j

      

j

2

so the expression evaluates to 4-2 = 2

.

i

has been increased, so it matters now 5

; j

changed by the code in the switch statement.

+6


source


through initialization



i=4;
j=2; 

switch(i++-j) {  // Expression evaluates as 4-2 = 2.
    // new value for i=5 since i++ executed
    case 3: i++; break; // skipped
    case 1: j++; break; // skipped
    case 2: j+=2; break; // Executed, hence  evaluates as 2+2 = 4.
    case 5: i+=2; break; // Skipped
    default: i +=5; break; // Skipped
    }

    System.out.println(i);  // Prints out 5
    System.out.println(j);  // Prints out 4

      

+1


source


In the switching condition, the value of the expression will be 4 - 2 = 2.

Then, after this value, i becomes 5.

Then case 2: will be executed, j = 2, j + = 2 will be 4.

So the output will be:

five

4

0


source







All Articles