Main Content

Incorrectly indented statement

Statement indentation incorrectly makes it appear as part of a block

Since R2020a

Description

This defect occurs when the indentation of a statement makes it appear as part of an if, else or another block but the arrangement or lack of braces actually keeps the statement outside the block.

Risk

A developer or reviewer might incorrectly associate the statement with a block based on its indentation, leading to an incorrect assumption about the program logic.

For instance, in this example:

if(credentialsOK())
   login=1;
   setCookies();
the line setCookies(); is not part of the if block, but the indentation suggests otherwise.

Fix

If you want a statement to be part of a block, make sure that the statement is within the braces associated with the block. To identify the extent of a block, on the Source pane, click the opening brace.

If an if, else or while statement has no braces following the condition, only the next line on an execution path up to a semicolon is considered part of the if, else or while block. If you want subsequent lines to be included in the block, wrap the lines in braces.

For instance, in the preceding example, to include both statements in the if block, use:

if(credentialsOK()) {
   login=1;
   setCookies();
}

Examples

expand all

int switch1, switch2;

void doSomething(void);
void doSomethingElse(void);

void func() {
    if(switch1) 
        if(switch2)
            doSomething();
    else
        doSomethingElse();
}

In this example, the else is indented as if it is associated with the first if. However, the else is actually associated with the second if. The indentation does not match the actual association and might lead to incorrect assumptions about the program logic.

Correction – Use Braces Appropriately

If you want the else to be associated with the first if, use braces to mark the boundaries of the first if block.

int switch1, switch2;

void doSomething(void);
void doSomethingElse(void);

void func() {
    if(switch1) { 
        if(switch2)
            doSomething();
    }
    else
        doSomethingElse();
}

Result Information

Group: Good practice
Language: C | C++
Default: Off
Command-Line Syntax: INCORRECT_INDENTATION
Impact: Low

Version History

Introduced in R2020a