-3
int x = 12;
false && x++;

After this snippet executes, x still has the value 12. If the ++ operator has higher precedence than &&, why isn't x incremented? Is there an explanation for this is or is it one of those things that you just accept? I am sorry if this is answered somewhere else. I did not come across it in my search.

Thank you for your time.

  • Look up short-circuit evaluation. The place you'd come across it is when a book introduces `&&`, `||` and `!`. – chris Jul 21 '14 at 01:15
  • 1
    possible duplicate of [How does C++ handle &&? (Short-circuit evaluation)](http://stackoverflow.com/questions/5211961/how-does-c-handle-short-circuit-evaluation) – M.M Jul 21 '14 at 01:15
  • 1
    @0x499602D2 Did you mix up left and right? – nhgrif Jul 21 '14 at 01:17
  • 3
    In case it is unclear, the precedence gives you `( false && (x++) )`. This does not imply that `x++` is executed first; it just means that the thing being `++`'d is `x`, as opposed to `(false&&x)` . – M.M Jul 21 '14 at 01:17
  • Be aware overloaded logical operations don't perform short-circuiting. I'm not how that would effect your example if x were a class. – Neil Kirk Jul 21 '14 at 01:18
  • Precedence and order of evaluation are two completely different things. The former defines how the results of evaluation are used. Normally, the order of evaluation is unspecified. In this case, there's an exception - short-circuit evaluation. – chris Jul 21 '14 at 01:18
  • @NeilKirk `bool` does not have overloaded operators so it would make no difference in this case. `x++ && false` (if `x++` returned reference to `x`) would be a different kettle of fish. – M.M Jul 21 '14 at 01:19
  • @chris Thanks for your response. When you say results of evaluation, do you simply mean obtaining for example the values of variables or is there more to it? – user3837835 Jul 21 '14 at 04:51
  • @user3837835, Yes, and then cascading the results of the operators as well. Matt's parenthesized example is nice for demonstrating precedence. – chris Jul 21 '14 at 12:12

1 Answers1

0

It checks for the false which is actually false for x=12 so it skips the incrementation of x as 13. if you swap the places as x++ && false then it would do x=13 and then skip the false leaving x with an incrementation of 1.

Shayan Ahmad
  • 952
  • 8
  • 17