Detecting "=" instead of "==" typos in the condition

Is there a way to get g ++ to throw a compile error if I use =

instead ==

inside an if condition in C ++? I've made this typo a couple of times and it's annoying to track down. I.e:

if (x=5){ //bad - sets x equal to 5
   //do something
}    

      

+3


source to share


3 answers


Option

-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.

+6


source


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.

+1


source


Yoda's condition is a simple, compiler-independent solution: if (5=x){statement}

won't compile.

0


source







All Articles