#3. The condition in an "if" statement should be a simple boolean expression with no side effects

The expression inside an if statement should be boolean, simple, and have no side effects.

In C++, every statement is an expression of a certain type. It may be an ordinary type, such as boolint or a user-defined type such as Customer), or a special type called void which basically means "no type".

In C++ the expression inside the pair of brackets will be understood as a boolean expression. Some people carry the habit from their C days and pass an as int an argument to the if. Other people even use a pointer, so that the if will check whether it is NULL and will evaluate to true in that case. Don't do it - it makes the code less readable and a step closer to being error prone.

Guideline #2 advised you to avoid implicit type conversions. This is a very good place to start applying it. The if statement requires a bool, so why pass it anything else?

Don't overcomplicate things by putting several actions together. Don't use complex commands which may succeed or not, returning a boolean which indicates success, as conditions inside if statements. Don't write assignments or, worse, variable declarations in the condition. In short, keep it simple.

It's better to separate the list of things that you need to do (check whether the object, whatever it is is connected, and then save to file) from a conditional action which you will perform if the result of one of these actions is not satisfactory.


[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book discusses conditionals in Chapter 15. In particular, see Section 15.1 "if statements" (pages 355-360) and the checklist at the end of the chapter (page 365).


Popular posts from this blog

#2. Make all type conversions explicit

#13. Organize your code in classes

#8. Define variables as close as possible to where they are used