Methods for avoiding common typo bugs
So I just spent the last few hours pouring over code trying to figure out the source of a bug only to find that my error was none other than the obvious开发者_如何学Pythonly wrong but compiler accepted:
if (a = b)
where it should have been
if (a == b)
What do you guys do to safeguard against these frustrating errors? What other common "obviously wrong, but compiler won't complain" bugs should I also watch out for?
The best thing you can do is to stick with the miscellaneous -W/-pedantic
options that the compiler makes available to you..
take a look here, there are many warnings you can enable to prevent many kinds of error, but you can't do anything about some errors except using yourself to prevent them :)
Most compilers provide options to give warnings in these situations. These are typically called "lint" warnings after the name of an early program to provide them for C source code (in the early days C compilers didn't have them built in, but they mostly do now). You might check to see you're enabling all warnings your compiler provides. If your compiler doesn't provide lint features, look into a good lint tool.
many people do Edit: take GMan's advice and please don't actually adopt this style; it's ugly, hard to read, and totally unnecessarily if you just compile with warnings.if(0 == var)
for literal numbers, because 0 = x;
is a compiler error. For if(a = b)
, I don't know any general solution.
Another example of ways to avoid typos is putting braces in for/while/if blocks. I have seen:
if(x)
doSomething();
somethingElse();
cause problems for example if the dev wasnt paying attention, had tabs/spaces screwed up so indentation was wrong or whatever. Removing the doSomething()
line, or adding stuff to the if()
block requires changes on other lines. Safer is:
if(x)
{
doSomething();
}
somethingElse();
One common problem for me is not checking that a pointer exists (not NULL) before using it. This problem has created many unexpected breaks in my code.
精彩评论