Main Content

MISRA C++:2023 Rule 22.4.1

The literal value zero shall be the only value assigned to errno

Since R2024b

Description

Rule Definition

The literal value zero shall be the only value assigned to errno.

Rationale

Several C++ Standard Library functions set errno to non-zero values to indicate error conditions. To check for errors following a call to one of these functions, you can set errno to zero before the call and check for nonzero values following the call. For this usage, you only need to set errno to the literal value zero.

This rule prevents the use of errno in other contexts. For instance, do not use errno for error-reporting in a custom library function that you create. C++ provides more superior methods for error-handling in these contexts.

Polyspace Implementation

The rule checker reports a violation if a nonzero value is assigned to the variable errno defined in the header <cerrno>.

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 <cerrno>
#include <cstdio>

#define ZERO (0)
int getErrno();

void test_errno(int val) {
    int null = 0;
    constexpr int zero = 0;

    errno = 0;                  // Compliant - Literal value zero.
    errno = ZERO;               // Compliant - Expands to literal value zero.

    FILE* file = fopen("/tmp/foo", "w+");
    if (errno == EISDIR) {      // Compliant 
        // ...
    }

    errno = null;               // Noncompliant
    errno = zero;               // Noncompliant
    errno = 3*(2-2);            // Noncompliant

    errno = 1;                  // Noncompliant
    errno++;                    // Noncompliant
    errno = errno + 1;          // Noncompliant
    errno += 2;                 // Noncompliant
    errno = getErrno();         // Noncompliant
    errno = val;                // Noncompliant
    errno = E2BIG;              // Noncompliant

    if (errno=EBUSY) {          // Noncompliant - Assignment in if()
    }
}

This example shows various assignments to the variable errno defined in the header <cerrno>.

  • The first two assignments show compliant usages of errno where the literal value 0 is assigned to errno before calling the Standard Library function fopen() and errno is checked for error values following the call.

  • All other assignments are noncompliant because a nonzero value is assigned to errno. In your code, you might be using an assignment of this kind if you implement error handling in a function using errno.

Check Information

Group: Diagnostics library
Category: Required

Version History

Introduced in R2024b