Hi, everyone.
what's the difference between: if (value = 1011) and if (value == 1011)?
int value = 1011.
Thanks
adam
From the reference for the if structure:
Beware of accidentally using the single equal sign (e.g.
if (x = 10)). The single equal sign is the assignment operator, and setsxto 10 (puts the value 10 into the variablex). Instead use the double equal sign (e.g.if (x == 10)), which is the comparison operator, and tests whetherxis equal to 10 or not. The latter statement is only true ifxequals 10, but the former statement will always be true.This is because C++ evaluates the statement
if (x=10)as follows: 10 is assigned tox(remember that the single equal sign is the (assignment operator)), soxnow contains 10. Then the 'if' conditional evaluates 10, which always evaluates toTRUE, since any non-zero number evaluates to TRUE. Consequently,if (x = 10)will always evaluate toTRUE, which is not the desired result when using an 'if' statement. Additionally, the variablexwill be set to 10, which is also not a desired action.
Great!
Sorry for my messed.
then I feel that it's easy to compare when used: if (value == 1) , no easy to use: if (value == 1011) or other number like 2011, why?
No problem. We see this often and I even forget == once in a while. If you enable all compile warnings in File, Preferences, you will get a warning if you do make that mistake.
int number = 17;
void setup()
{
Serial.begin(115200);
if(number = 17)
{
Serial.println("equal");
}
}
void loop()
{
}
\sketch_jul11a.ino:6:15: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
if(number = 17)
~~~~~^~
Thank you groundFungus.
What do you mean by that?
If you flip it around it will cause an error and not let you make that mistake at all.
int number = 17;
void setup()
{
Serial.begin(115200);
if(17 = number)
{
Serial.println("equal");
}
}
void loop()
{
}
sketch_jul11a:6:13: error: lvalue required as left operand of assignment
if(17 = number)
^~~~~~
exit status 1
lvalue required as left operand of assignment
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
