Detecting "=" instead of "==" typos in the condition
-Wparentheses
specifically warns of such cases, which is also part of the option -Wall
.
From the gcc documentation :
-Wparentheses
Warn if parentheses are omitted in certain contexts, such as when there is an assignment in a context where a true value is expected, or when statements are nested, whose precedence people are often confused about.
...
When there is potential for this confusion, GCC issues a warning when this flag is specified. To eliminate the warning, add explicit parentheses around the innermost if statement, so there is no other way the else can belong to the enclosed if.
which can be converted to an error by specifying -Werror=parentheses
.
note that
if(x=5) {...}
is legal and the standard does not require such diagnostics. But an implementation is allowed to provide any number of such useful warnings.
source to share
You can refer to this with a different coding style: many programmers I know prefer to use the style if (5 == x)
for this reason, because if you forget the equal sign, you end up with if (5 = x)
one that doesn't compile (5 is not an lvalue).
Aside from being a bit simpler than tinkering with compiler options, it also portable to any standard C ++ compiler.
IMO, the only drawback is that it doesn't read so naturally if you're not used to it; in English it is more common to say "if x is 5" instead of "if 5 is x". Of course, since equality is commutative, both are correct, but most people prefer the former. This is one of those cases where something that feels stylistically wrong helps you write better code.
source to share
Yoda's condition is a simple, compiler-independent solution: if (5=x){statement}
won't compile.
source to share