I\'m reading some lecture notes of my C++ lecturer and he wrote the following:
- Use Indentation // OK
- Never rely on operator preced
To add to the very sensible suggestions above, one example I encountered while refactoring some code of where this becomes critical was as follows: I was altering a very large codebase to switch from one API to another. The first API had a call to set Company Id as follows:
setCompIds( const std::string& compId, const std::string& compSubId );
whereas the replacement needed two calls:
setCompId( const std::string& compId );
setCompSubId( const std::string& compSubId );
I set about changing this using regular expressions which was very successful. We also passed the code through astyle, which really made it very much more readable. Then, part way through the review process, I discovered that in some conditional circumstances it was changing this:
if ( condition )
setCompIds( compId, compSubId );
To this:
if ( condition )
setCompId( compId );
setCompSubId( compSubId );
which is clearly not what what was required. I had to go back to the beginning do this again by treating the replacement as completely within a block and then manually altering anything that ended up looking goofy (at least it wouldn't be incorrect.)
I notice that astyle now has the option --add-brackets
which allows you to add brackets where there are none and I strongly recommend this if you ever find yourself in the same position as I was.