Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this switch statement evaluated?

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
like image 838
user3601148 Avatar asked Aug 11 '26 14:08

user3601148


2 Answers

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.

like image 97
Tommy Avatar answered Aug 13 '26 03:08

Tommy


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
like image 45
Suji Avatar answered Aug 13 '26 05:08

Suji