Expressions

Rec.: use parentheses to clarify the order of evaluation in expressions.

Rec.: write boolean expressions in complete form.



Even if you have a deep knowledge of the language, do not assume your code will be always read and maintained by people with the same knowledge. For example, most programmers do not know or remember the rules of operator precedence and associativity, so it is difficult for them to read and understand expressions such as:

    if( a > b || a >= c && a < d ) ... // Very difficult to read, may require reading TFM!

The above can be much improved by using parentheses in the proper places:

    if( (a > b) || ((a >= c) && (a < d)) ) ... // Aha, better!

The fact that the latter form can be read and understood by everyone, makes it also less prone to errors.

Rec.: use parentheses to clarify the order of evaluation in expressions.

Many people also find it confusing when numeric expressions are used straight as if they were boolean (an unremarkable feature of the C syntax):

    if( !strcmp( s, t ) ) ... // So are the strings same or different?
    void * p;

    if( !p ) ... // Easier but still confusing to some!

When those expressions are found, it may take up to a few seconds to mentally reconstruct the full expression and understand how it works. It is preferrable to be clear from the beginning and use the full form:

    if( strcmp( s, t ) == 0 ) ... // Ok, now I see...

    if( p != NULL ) ... // Better, can also be (p != 0) in C++

Rec.: write boolean expressions in complete form.

Top: Table of content  |  Previous: Declarations: classes and class members (C++)  |  Next: Flow control

Copyright (c) 2003 Alessandro Scotti. All rights reserved.