Iron Attorney Iron Attorney - 3 months ago 9
C++ Question

Why can't I perform *= operations in an if statement?

While doing a codewars challenge, I though of a way to compact my code a bit that I would of thought would work, but doesn't.

My initial code snippet is as follows:

while (true)
{
ballSeen++; // Seen on way down

newHeight *= bounce;
if (newHeight < window) break;

ballSeen++; // If seen after bounce
}


I thought maybe I could chuck the multiplication into the if statement and make it look like this:

while (true)
{
ballSeen++; // Seen on way down
if (newHeight *= bounce < window) break;
ballSeen++; // If seen after bounce
}


The second way gets an error. I admit it's not something I've seen before, and I wasn't certain it would work... but I'm curious as to why it doesn't work. I would of thought while performing the comparison with window, it would just perform the calculation.

Answer

As the comments have already suggested you, there is a problem with operators precedence.

In the reference you can see the operator < has more precedence than the operator *=.

Then the statement:

if (newHeight *= bounce < window) break;

Checks bounce < window before.

You should try

if ((newHeight *= bounce) < window) break;

EDIT

Another, maybe more readable, solution could be fine with the usage of the comma operator.

It becomes:

if (newHeight *= bounce, newHeight < window) break;

This allows you to save one line, as well.