This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 6.0.1 - Block scope declarations [1] shall not be visually ambiguous
Category: Required
Analysis: Decidable,Single Translation Unit
Amplification
A block scope declaration [1] is visually ambiguous when:
- It declares a function; or
- It declares an object with redundant parentheses surrounding the object’s name.
Note: this rule does not apply to Lambda expressions as they are not function declarations.
Rationale
Due to the syntactic similarity of function declarations and object definitions that use parentheses for initialization, it is possible that a
declaration may be misinterpreted by the developer. For example, a function declaration may be interpreted as an object definition, which is sometimes
referred to as the most-vexing parse.
The C++ grammar allows for redundant parentheses around a declarator, where what appears to be the construction of an object with a single argument
to the constructor is actually the declaration of an object of that "argument" name and a call to the default constructor.
Note: using braces instead of parentheses for object initialization, where possible, avoids the most-vexing parse.
Example
class A {};
void f1()
{
void f2(); // Non-compliant - function declaration at block scope
A a1(); // Non-compliant - appears to declare an object with no
// arguments to constructor, but it declares a function
// 'a1' returning type 'A' and taking no parameters.
A a2; // Compliant
}
int32_t j;
void f3()
{
int32_t ( j ); // Non-compliant - declares 'j' (using redundant parentheses)
int32_t { j }; // Compliant with this rule, but violates "See also"
} // - Creates a temporary object with value 'j'.
Glossary
[1] Declaration
A declaration introduces the name of an entity into a translation unit (see [basic.def]/1).
An entity may be declared several times. The first declaration of an entity in a translation unit is
called an introduction [2]. All subsequent declarations are called redeclarations [3].
A definition [4] is a declaration, as described in [basic.def]/2.
[2] Introduction
See declaration [1].
[3] Redeclaration
See declaration [1].
[4] Definition
See declaration [1].
Copyright The MISRA Consortium Limited © 2023