AutosarC++19_03-M6.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
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
If the bodies of these constructs are not compound statements, then errors can occur if a developer fails to add the required braces when attempting to change a single statement body to a multi-statement body.
Requiring that the body of these constructs shall be a compound statement (enclosed within braces) ensures that these errors cannot arise.
Example
if ( test1 ); // Non-compliant - accidental single null statement
{
x = 1;
}
if ( test1 )
{
x = 1; // Compliant - a single statement must be in braces
}
else if ( test2 ) // Compliant - no need for braces between else and if
{
x = 0; // Compliant – a single statement must be in braces
} else // Non-compliant
x = 3; // This was (incorrectly) not enclosed in braces
y = 2; // This line was added later but, despite the
// appearance (from the indent) it is actually not
// part of the else, and is executed unconditionally
Note that this example assumes a particular style for the layout of compound statements and their enclosing braces. This style is not mandated, but a style should be defined within the style guide for the project.
Note
For legal reasons, this rule’s description is not part of the public documentation.