Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How increment operator works in switch case?

It prints output from case 10: but prints x=11 how? after which line it increments the value of x

int x = 10;
switch (x++) {
case 10:
        System.out.println("case 1 ::: "+x);
        break;
case 11:
    System.out.println("case 2 ::: "+x);
    break;
default:
    System.out.println("default ::: "+x);
}

OUTPUT

case 1 ::: 11
like image 540
BHAR4T Avatar asked Mar 17 '26 13:03

BHAR4T


1 Answers

The post increment operator x++ increments x but returns the previous value of x - 10. Therefore the switch statement gets the value 10 (that's the value of the x++ expression), and executes the block of case 10:, at which point System.out.println("case 1 ::: "+x); prints the incremented value of x - 11.

like image 111
Eran Avatar answered Mar 19 '26 02:03

Eran