Main Content

Macro terminated with a semicolon

Macro definition ends with a semicolon

Since R2020a

Description

This defect occurs when a macro that is invoked at least once has a definition ending with a semicolon.

Risk

If a macro definition ends with a semicolon, the macro expansion can lead to unintended program logic in certain contexts, such as within an expression.

For instance, consider the macro:

#define INC_BY_ONE(x) ++x;
If used in the expression:
res = INC_BY_ONE(x)%2;
the expression resolves to:
res = ++x; %2;
The value of x+1 is assigned to res, which is probably unintended. The leftover standalone statement %2; is valid C code and can only be detected by enabling strict compiler warnings.

Fix

Do not end macro definitions with a semicolon. Leave it up to users of the macro to add a semicolon after the macro when needed.

Alternatively, use inline functions in preference to function-like macros that involve statements ending with semicolon.

Examples

expand all

#define WHILE_LOOP(n) while(n>0);

void performAction(int timeStep);

void main() {
    int loopIter = 100;
    WHILE_LOOP(loopIter) {
        performAction(loopIter);
        loopIter--;
    }
}

In this example, the defect occurs because the definition of the macro WHILE_LOOP(n) ends with a semicolon. As a result of the semicolon, the while loop has an empty body and the subsequent statements in the block run only once. It was probably intended that the loop must iterate 100 times.

Correction – Remove Semicolon from Macro Definition

Remove the trailing semicolon from the macro definition. Users of the macro can add a semicolon after the macro when needed. In this example, a semicolon is not required.

#define WHILE_LOOP(n) while(n>0)

void performAction(int timeStep);

void main() {
    int loopIter = 100;
    WHILE_LOOP(loopIter) {
        performAction(loopIter);
        loopIter--;
    }
}

Result Information

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

Version History

Introduced in R2020a