Mistakenly writing = instead of == when comparing
suggest changeThe = operator is used for assignment.
The == operator is used for comparison.
One should be careful not to mix the two. Sometimes one mistakenly writes
/* assign y to x */
if (x = y) {
/* logic */
}
when what was really wanted is:
/* compare if x is equal to y */
if (x == y) {
/* logic */
}
The former assigns the value of y to x and checks whether that value is non-zero, instead of comparing, which is equivalent to:
if ((x = y) != 0) {
/* logic */
}
There are times when testing the result of an assignment is intended and is commonly used, because it avoids having to duplicate code and having to treat the first time specially. Compare
while ((c = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { /* POSIX */
switch (c) {
...
}
}
versus
c = getopt_long(argc, argv, short_options, long_options, &option_index);
while (c != -1) {
switch (c) {
...
}
c = getopt_long(argc, argv, short_options, long_options, &option_index);
}
Modern compilers recognise this pattern and do not warn when the assignment is inside parentheses, as above, but may warn about other uses. For example:
if (x = y) /* warning */
if ((x = y)) /* no warning */
if ((x = y) != 0) /* no warning; explicit */
Some programmers use the strategy of putting the constant to the left of the operator (commonly called Yoda conditions). Because constants are not modifiable lvalues, this style of condition causes the compiler to diagnose an error if the wrong operator was used.
if (5 = y) /* Error */
if (5 == y) /* No error */
However, this severely reduces the readability of the code and is not considered necessary if the programmer follows good C coding practices, and it doesn’t help when comparing two variables, so it isn’t a universal solution. Compilers can warn about if (x = y) without requiring the constant to be on the left.