A very simple typo resulted in a bug:
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:
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?
(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?
- Temporarily compile with more advanced compiler versions
- Temporarily compile with stronger warnings
- Use tools such as Cppcheck to 2x check your code
- Try compiling with a completely different compiler
- 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.”