Even Higher Warning Levels

When compiling code in MS Visual Studio .Net I always turn warning levels up to 4 (/W4). I’ll end up getting some warnings about things I don’t care about, such as converting an int to true or false when it’s something I did on purpose or not referencing a formal parameter of a function, but it’s still better for spotting potential problems.

For example, one warning that many people often ignore but can be a big problem is “C4706: assignment within conditional expression”. It’s the difference between:

if( ( x = a ) )
{
do something;
}

int x = a;
if( ( x ) )
{
do something;
}

Both pieces of code do the same thing: Set the variable X equal to A and then check whether X is nonzero. The problem with the first piece is that someone reading your code has no idea whether you meant to assign A to X or check whether X is equal to A. Even worse, one small typo and you could be doing assignment when you meant comparison. It’s better to break it into two statements like the second piece of code so you and everyone else knows what you intended to do AND that it actually happens the way you intend.

When compiling using g++ on Linux, I’ve always used -Wall. Since around 1995 I’ve been using that thinking it would warn me about everything it saw. There are a few things that Visual Studio would warn me about that g++ wouldn’t catch and the more it happened the more I started to wonder why. Cue the documentation.

AHA! While browsing the commandline parameter list for the GNU compiler, I found two interesting switches: -Wextra and -pedantic.

If you use those two switches, you’ll get what Visual Studio gave you and more. Much more. The bad news: I’m doing far too many ‘deprecated string conversions’. The good news: I’ve spotted even more potential problems and can fix them before they become big problems.

Some people think warnings are just annoyances. It’s a better idea to treat them as run-time errors. It might be more of a pain in the butt when writing code, but it’ll help in the long run. Thank your nitpicky compiler, it’s trying to protect you.

It’s amazing what you can do when you read the documentation…