Main Content

MISRA C++:2023 Rule 0.1.2

The value returned by a function shall be used

Since R2024b

Description

Rule Definition

The value returned by a function shall be used.

Rationale

The unused return value might indicate a coding error or oversight.

Overloaded operators are excluded from this rule because their usage must emulate built-in operators which might not use their return value.

If you want to deliberately ignore the return value of a function, cast the return value to void.

Polyspace Implementation

The checker reports a violation if:

  • The value returned by a function with non-void return type remains unused and not explicitly cast to a void type.

  • A lambda, std::function object, or a user-defined operator() is invoked using the function call syntax, and its return value remains unused.

The checker does not report violations for the functions memcpy, memset, memmove, strcpy, strncpy, strcat, strncat because these functions simply return a pointer to their first arguments.

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>
#include <new>
#include <algorithm>
#include <cstdint>
#include <vector>

int assignMemory(int * ptr)
{
    int res = 1;
    ptr = new (std::nothrow) int;
    if(ptr==NULL)
        {
            res = 0;
        }
    return res;
}

void main()
{
    int val;
    int status;
    std::vector<std::int8_t> numVec{10,10,20,20,30,40,50,50,60};

    assignMemory(&val);  //Noncompliant
    status = assignMemory(&val);  //Compliant
    (void)assignMemory(&val);  //Compliant

    numVec.erase(std::unique(numVec.begin(), numVec.end()), numVec.end());  // Noncompliant
}

In this example, Polyspace reports a violation on calls to the assignMemory() function and std::vector::erase() method when their return values are not used or cast to void.

Check Information

Group: Language Independent Issues
Category: Required

Version History

Introduced in R2024b