Main Content

MISRA C++:2023 Rule 7.11.1

nullptr shall be the only form of the null-pointer-constant

Since R2024b

Description

Rule Definition

nullptr shall be the only form of the null-pointer-constant

Rationale

With nullptr, function overloading works more predictably. When using 0 or NULL, the value can be interpreted as an integer, leading to unexpected behavior if multiple overloads are available. nullptr unambiguously identifies a null pointer, ensuring the correct function overload is chosen when a null pointer is intended as an argument.

Using a named constant or macro to represent a null value in your code does not change the resulting compiled code. The pointer is still assigned a null value, and the distinction between the two approaches is abstracted away during compilation.

Polyspace Implementation

The rule checker reports a violation when the code uses any other integral literal, including NULL, to represent the null-pointer constant instead of using nullptr.

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

#include <iostream>

void foo(int* ptr) {
    std::cout << "foo(char* ptr) called" << std::endl;
}

void foo(int i) {
    std::cout << "foo(int i) called" << std::endl;
}

int main() {
    foo(nullptr);    //Compliant
    foo(NULL);       //Noncompliant

    return 0;
}

In this example, foo(nullptr) unambiguously calls the overload that takes a pointer. However, foo(NULL) calls the integer overload because NULL is defined as 0 in this scenario. This might not be what the programmer intended if they meant to pass a null pointer value to foo().

Check Information

Group: Standard Conversions
Category: Required

Version History

Introduced in R2024b