Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 405
knittl Avatar asked Oct 28 '10 15:10

knittl


People also ask

Can 0 be a value of x?

Answer: x to the power of 0 is 1. According to the zero property of exponents, any number other than 0 raised to the power of zero is always equal to 1. Hence x to the power of 0 can be written as x0.

What is the answer if x is 0?

The solution x = 0 means that the value 0 satisfies the equation, so there is a solution. “No solution” means that there is no value, not even 0, which would satisfy the equation. Also, be careful not to make the mistake of thinking that the equation 4 = 5 means that 4 and 5 are values for x that are solutions.

What is X 0 called?

a y-intercept is a point on the graph where x is zero.

Is X 0 1 or X?

Any number to the zero power always gives one. xa * x-a = xa * 1/xa: This means that any number x0 = 1.


1 Answers

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.

like image 165
Steve Jessop Avatar answered Nov 06 '22 02:11

Steve Jessop