views:

151

answers:

2

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?

+11  A: 

Yes it is well defined. && introduces a sequence point.

Prasoon Saurav
Huh, I have the feeling that you or others are using some feed like Twitter in order to answer so darned fast. When I first see a question it's generally already answered... ?
Alf P. Steinbach
@Alf P. Steinbach, click the "questions" link once in a second
Harmen
@Alf: When I saw this question it was unanswered and so I answered it. The trick is : Refresh the "New questions" page at least once in 10 seconds. `;-)`
Prasoon Saurav
so, `array[x]` uses the old or the new value?
knittl
@knittl : The new value.
Prasoon Saurav
hmm I thought it would get the old value... oh well
VJo
+5  A: 

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.

Steve Jessop
Zack
knittl
Armen Tsirunyan
@Zack - Since the dawn if C++. Only `?:` `::` `.` `.*` (and maybe more, can't remember right now) cannot be overloaded
Armen Tsirunyan
@Zack: certainly since the C++ standard was finalized, I don't know about before that.
Steve Jessop
Steve Jessop
@Armen: if both x is int and array is an array then it's impossible to overload for them.
Armen Tsirunyan
Steve Jessop