How does the compiler interpret this switch statement? I assume the contents inside the switch statement is (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
Break it down:
i++-j
++ has higher precedence than - so that's:
(i++)-j
The ++ is the postfix increment — it'll evaluate to the value of i before the increment. The initial value of i is 4 so that's:
4-j
j is 2 so the expression evaluates as 4-2 = 2.
i has been incremented so now has the value 5; j is modified by the code in the switch statement.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With