Main Content

MISRA C++:2023 Rule 11.6.1

All variables should be initialized

Since R2024b

Description

Rule Definition

All variables should be initialized.

Rationale

This rule encourages the practice of initializing variables at the point where they are declared. Initializing variables at the point of declaration prevents accidental read of the variables while they are still uninitialized.

The rule also encourages initialization of variables with real values, that is, values that will be used when read next. This initialization strategy implies that you delay the declaration of variables till they are ready to be used.

Polyspace Implementation

The rule checker reports a violation when a variable is not initialized at declaration. Exceptions include:

  • Global and static non-pointer variables that are zero-initialized by default.

  • Class objects that are initialized using default constructors.

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

In this example, the declaration of the variable response in the getResponse() function violates the rule because the variable is not initialized at declaration. The declaration of the same variable in the btnResponse() function avoids the rule violation by also initializing the variable at the same time.

#include <cstdint>

extern int32_t onResponse(void);
extern int32_t offResponse(void);

int32_t getResponse(bool btn)       
{
    int32_t response;                  // Noncompliant
    if(btn)
        {
            response = onResponse();
        }
    else
        {
            response = offResponse();
        }
    return response;
}

int32_t btnResponse(bool btn)
{
    int32_t response = offResponse();  // Compliant
    if(btn)
        {
            response = onResponse();
        }
    return response;
}

Check Information

Group: Declarators
Category: Advisory

Version History

Introduced in R2024b