[previous] 3402 [next] Braces are needed to clarify the structure of this 'if'-'if'-'else' statement.
Bracing and Indentation REFERENCE - ISO:C90-6.6.4.1 The if statement - Semantics

Message 3402 is generated when 2 nested if statements are followed by a single else clause and the body of the first if statement is not a compound statement.

The absence of braces can be very misleading in such a situation because it is not obvious whether the else clause is related to the first or the second if statement. According to the ISO standard: "An else is associated with the lexically immediately preceding "else-less" if that is in the same block (but not in an enclosed block)."

Braces should always be used following an if or an else so as to avoid any possible confusion.

For example:


/*PRQA S 2017,2201,3120,3227,3408 ++*/

extern int foo(int i, int j)
{
    int r = 0;

    if (i > 0)                  /* Message 3402 */
        if (j > 0)              /* Message 2212 */
        {
            r = 1;
        }
    else
    {
        r = 2;
    }


    if (i > 0)                  /* Message 3402 */
        if (j > 0)              /* Message 2212 */
        {
            r = 1;
        }
        else
        {
            r = 2;
        }

    return r;
}


MISRA-C:2004 Rules applicable to message 3402:

Rule  14.9  (Required) An if (expression) construct shall be followed by a compound statement. The else keyword shall be followed by either a compound statement, or another if statement.


See also:

QA·C Source Code Analyser 8.1
MISRA-C:2004 Compliance Module 3.2
© 2012 Programming Research.
www.programmingresearch.com
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index Contents