Main Content

MISRA C++:2023 Rule 6.0.1

Block scope declarations shall not be visually ambiguous

Since R2024b

Description

Rule Definition

Block scope declarations shall not be visually ambiguous.

Rationale

If you declare a function at block scope, it is often not clear if the statement is a function declaration or an object declaration with a call to the constructor. For instance, these declarations are ambiguous:

  • ResourceType aResource();

    It is not immediately clear if aResource is a function returning a variable of type ResourceType or an object of type ResourceType.

  • TimeKeeper aTimeKeeper(Timer());

    It is not immediately clear if aTimeKeeper is an object constructed with an unnamed object of type Timer or a function with an unnamed function pointer type as parameter. The function pointer refers to a function with no argument and return type Timer.

This rule does not check for ambiguous declarations in the global scope.

Polyspace Implementation

The rule checker flags ambiguous function declarations that can be mistaken for an object declaration.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

class A {
};

void b1() {
    void func(); //Noncompliant
    A a();   //Noncompliant
}

In this example, the declarations of func and a are in the block scope of b1.

The second function declaration can cause confusion because it is not clear if a is a function that returns an object of type A or a is itself an object of type A.

In this example, aResource might be used as an object but the declaration syntax indicates a function declaration.

class ResourceType {
      int aMember;
    public:
      int getMember();
};

void getResource() {
    ResourceType aResource();
}
Correction — Use {} for Object Declaration

One possible correction (after C++11) is to use braces for object declaration.

class ResourceType {
      int aMember;
    public:
      int getMember();
};

void getResource() {
    ResourceType aResource{};
}

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2024b