1
int num = 5;
if (num != 5 & num++ != 6 | (num = num--) == 6)
System.out.println("true " + num);
else
System.out.println("false " + num);

The output of this code is "true, 6". I need help on understanding how num evaluates to the number 6 through the boolean statement.

dphil1
  • 113
  • 4
  • 1
    Why do people specifically look for fringe cases that no reasonable coder would use. Using the pre- and post-decrement operators in the middle of an expression is just asking for trouble, and it may not be portable to another compiler. – NomadMaker Aug 20 '20 at 20:29
  • @NomadMaker: Because this is the kind of trickery that professors or certifiers can put on tests. Which is why I'll never be a certified Java developer. – Gilbert Le Blanc Aug 20 '20 at 21:02
  • My point is that this is the sort of thing that should not be on tests. – NomadMaker Aug 20 '20 at 22:35

1 Answers1

1

As Colin here has put, there is actually a lot going on here!

Let me take one half of the expression in the if condition first;

    num != 5 & num++ != 6 

Now what this does is first evaluates that num is not equal to 5 ,ie, false

Second, evaluates that num is not equal to 6 ,ie, true (postincrement)

Third, evaluates for the bitwise AND operator ,ie, false & true
Making the result false for this half of the expression

Forth, increments the value of num ,ie, from 5 to 6


Now for the remaining expression;

    (num = num--) == 6

This part of the expression first evaluates the bracket.

Here num-- decrements num and returns the old value which is 6 currently. Then this value is assigned to num again it's a classic postincrement/assignment confusion (Do see https://stackoverflow.com/a/24564625/11226302 for detailed explanation)

Second, it evaluates if num is equal to 6 ,ie, true

That is how the value of num evaluates to 6 at the end of the expression.

This makes the second half of the expression true




After this the | bitwise inclusive OR operator takes precedence and evaluates the overall expression, which is

    false | true

Making it true.

Shivam Puri
  • 1,578
  • 12
  • 25