if (a=1) , what does it mean?

Oct 3, 2010 at 12:04pm
My compiler doesn't warn me if I write if (a=1) instead of if (a==1). Why? What does if (a=1) mean? Is it usable?
Last edited on Oct 3, 2010 at 12:05pm
Oct 3, 2010 at 12:12pm
if(a=1){}
is the same as
1
2
a = 1;
if(a){}
Oct 3, 2010 at 12:28pm
It's not the same, it's practically the same. The assignment operator returns a when done with the assignment. The if checks this value, in other words: a is assigned 1. a evaluates as output of the assignment operator (which is 1). The if checks a (which is 1) and is always executed (in this case).
The conclusion of this line of code is that a is assigned 1 and the if always evaluates to true (in this case). The == isn't an assignment operator, it checks for equality. (Is a equal to 1?)
Last edited on Oct 3, 2010 at 12:31pm
Oct 3, 2010 at 12:36pm
So this line:

a=b=c=d=e=f=g=h=i=j=k=l=1

Is correct!
Oct 4, 2010 at 12:46am
It is if all the variables are declared at that point.

The only time if (a=<value>) would evaluate to false is if <value> was zero.



edited so I don't know what Duoas is talking about... ;-p
Last edited on Oct 4, 2010 at 4:21am
Oct 4, 2010 at 1:57am
The only time if (a=<value>) would evaluate to true false is if <value> was zero.
:-)
Oct 4, 2010 at 3:36am
(or if the = operator was improperly overloaded) ;P
Oct 4, 2010 at 8:42am
shouldnt this be in the beginner forum??.....i am a noob at C++ and i did know this already from the tutorials on this website.
Topic archived. No new replies allowed.