Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

So can someone help me grasp all the (or most of the relevant) situations of an assignment inside something like an if(...) or while(...), etc?

What I mean is like:

if(a = b)

or

while(a = &c)
{
}

etc...

When will it evaluate as true, and when will it evaluate as false? Does this change at all depending on the types used in the assignment? What about when there are pointers involved?

Thanks.

like image 524
MetaGuru Avatar asked Jan 05 '10 02:01

MetaGuru


2 Answers

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

like image 142
Bruno Reis Avatar answered Oct 06 '22 23:10

Bruno Reis


An assignment "operation" also returns a value. It is the type and value of the expression. If handled by an if type statement:

  • while (expr)
  • do ... until (expr)
  • if (expr)
  • or the ternary operator (expr) ? (true value) : false value

expr is evaluated. If it is nonzero, it is true. If zero, it is false.

like image 31
wallyk Avatar answered Oct 06 '22 23:10

wallyk