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
source to share
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.
source to share
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
source to share