In C++ what causes an assignment to evaluate as true or false when used in a control structure?

In C++ an attribution evaluates to the value being attributed:

int c = 5; // evaluates to 5, as you can see if you print it out
float pi = CalculatePi(); // evaluates to the result
                          // of the call to the CalculatePi function

So, you statements:

if (a = b) { }
while (a = &c) { }

are roughly equivalent to:

a = b
if (b) { }
a = &c
while (&c) { }

which are the same as

a = b
if (a) { }
a = &c
while (a) { }

And what about those if (a) etc when they are not booleans? Well, if they are integers, 0 is false, the rest is true. This (one “zero” value -> false, the rest -> true) usually holds, but you should really refer to a C++ reference to be sure (however note that writting if (a == 0) is not much more difficult than if (!a), being much simpler to the reader).

Anyways, you should always avoid side-effects that obscure your code.

You should never need to do if (a = b): you can achieve exactly the same thing in other ways that are more clear and that won’t look like a mistake (if I read a code like if (a = b) the first thing that comes to my mind is that the developper who wrote that made a mistake; the second, if I triple-check that it is correct, is that I hate him! 🙂

Good luck

Leave a Comment