Control structures are code statements that impact the program’s control flow (e.g., if statements, for loops, etc.)
Why is this an issue?
While not technically incorrect, the omission of curly braces can be misleading and may lead to the introduction of errors during maintenance.
In the following example, the two calls seem to be attached to the if
statement, but only the first one is, and
checkSomething
will always be executed:
if (condition) // Noncompliant
executeSomething();
checkSomething();
Adding curly braces improves the code readability and its robustness:
if (condition) {
executeSomething();
checkSomething();
}
The rule raises an issue when a control structure has no curly braces.
Resources
- MISRA C:2004, 14.8 - The statement forming the body of a switch, while, do … while or for statement shall be a compound statement
- MISRA C:2004, 14.9 - 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
- MISRA C++:2008, 6-3-1 - The statement forming the body of a switch, while, do … while or for statement shall be a compound statement
- MISRA C++:2008, 6-4-1 - An if (condition) construct shall be followed by a compound statement. The else keyword shall be followed by either a
compound statement, or another if statement
- MISRA C:2012, 15.6 - The body of an iteration-statement or a selection-statement shall be a compound-statement
- CERT, EXP19-C. - Use braces for the body of an if, for, or while statement