In C++ what causes an assignment to evaluate as true or false when used in a control structure?
c++
Solution
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
Problem
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.