Use <constant> == <value>This tip submitted by Webmaster on 2005-01-24 06:53:34. It has been viewed 24316 times.
Rating of 5.2 with 187 votes
When starting out, to avoid using a single equal sign instead of == to check equality, you can put the constant value on the left hand side:
int a; cin>>a; if(3 == a)
int a; cin>>a; if(a == 3)
In this way, if you accidentally write
if(3 = a)
then your compiler will generate an error about an "invalid lvalue", meaning that you can't assign the value of a to the number 3. (It already has a value.)
Another way of avoiding this problem is to turn on all compiler warnings and look for something like:
"suggest parentheses around assignment used as truth value"
This indicates that the result of an assignment (e.g., a = 3) is being used to check for truth. In some cases, this is reasonable -- for instance, when reading characters:
while((g = getchar()) != '\n')
Since the value of an assignment is the value assigned to the variable, this will work as expected. (For the same reason, something like a = 3 will always be true because it will evaluate to 3.
Help your fellow programmers! Add a tip!