Better Legacy C++ Code with Tools

A very simple typo resulted in a bug:

CString myTest(“foo”);
if( myTest.find(“o” < 0))  //should be find(“o”) < 0
//never gets here, regardless of find() test contents


Notice how the simple mis-placement of the ) on find() leads to this error, albeit compiled correctly. The compiler is actually converting this to pointer arithmetic and the address of the “o” string is always something and cannot be less than zero; hence this is always false. Switching to std::string yields the same:


#include <string>
int badChar()
std::string test(“abc”);
if (std::string::npos != test.find(“123” < 0)) return 1;
return foo; //returns 0 (zero)


This test was done w/ Visual Studio 2015 and default warning level of 3. So what can be done?
Running Cppcheck yields a weak warning:
(style) A pointer can not be negative so it is either pointless or an error to check if it is.


It’s weak in that errors should be more aggressively pointed out to err on the side of safety. But let’s not loose sight of the positive: it is helpful.


Alternatively, if the warning level is set to 4, a warning is generated:
‘<‘ : logical operation on address of string constant


This is good news!


If one is really pedantic, try compiling your code against a totally different compiler, such as gcc. On my Mac, this won’t even compile. However, using std::string::npos makes the original error even more difficult. It’s completely illogical and hurts to even visually scan it.


So then, getting back to the main point: what tools or actions are available to help ensure legacy code is great?
  1. Temporarily compile with more advanced compiler versions
  2. Temporarily compile with stronger warnings
  3. Use tools such as Cppcheck to 2x check your code
  4. Try compiling with a completely different compiler
  5. Limit use of platform or library data types such as ‘CString’ to where it’s absolutely needed. Use std::string as much as possible.


Today we have great tools: SSD drives, RAM, multi-processors, caches, etc. These resources give us a great opportunity to experiment, validate & grow while doing your daily work. The only thing your team will notice is higher quality work.


To quote David Cutler: “If you don’t put bugs in, you don’t have to take them out.”

Better Legacy C++ Code with Tools

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s