Search code examples
c++undefined-behaviorpost-increment

Is `x-- > 0 && array[x]` well-defined behavior in C++?


Can I use x on both sides of a boolean expression when I post-increment it on the left side?

The line in question is:

 if(x-- > 0 && array[x]) { /* … use x … */ }

Is that defined through the standard? Will array[x] use the new value of x or the old one?


Solution

  • It depends.

    If && is the usual short-circuiting logical operator, then it's fine because there's a sequence point. array[x] will use the new value.

    If && is a user (or library) defined overloaded operator, then there is no short-circuit, and also no guarantee of a sequence point between the evaluation of x-- and the evaluation of array[x]. This looks unlikely given your code, but without context it is not possible to say for sure. I think it's possible, with careful definition of array, to arrange it that way.

    This is why it's almost always a bad idea to overload operator&&.

    By the way, if ((x > 0) && array[--x]) has a very similar effect (again, assuming no operator overloading shenanigans), and in my opinion is clearer. The difference is whether or not x gets decremented past 0, which you may or may not be relying on.