C6031

warning C6031: return value ignored: called-function could return unexpected value

This warning indicates the caller doesn't check a function's return value for failure. Depending on which function is being called, this defect can lead to seemingly random program misbehavior. That includes crashes and data corruptions in error conditions or low-resource situations.

In general, it isn't safe to assume that calls to functions requiring disk, network, memory, or other resources will succeed. The caller should always check the return value and handle error cases appropriately. Also consider using the _Must_inspect_result_ annotation, which checks that the value is examined in a useful way.

Example

The following code generates this warning:

#include <stdio.h>
void f( )
{
    fopen( "test.c", "r" ); // C4996, C6031 return value ignored
    // code ...
}

To correct this warning, check the return value of the function as shown in the following code:

#include <stdio.h>
void f( )
{
    FILE *stream;
    if ( (stream = fopen( "test.c", "r" )) == NULL )
        return;
    // code ...
}

The following code uses safe function fopen_s to correct this warning:

#include <stdio.h>
void f( )
{
    FILE *stream;
    errno_t err;

    if ( (err = fopen_s( &stream, "test.c", "r" )) !=0 )
    {
        // code ...
    }
}

This warning is also generated if the caller ignores the return value of a function annotated with the _Check_return_ property as shown in the following code.

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    func(); //  Warning C6031
}

To correct the previous warning, check the return value as shown in the following code:

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    if ( func() ) {
        // code ...
    }
}

In cases where it is necessary to ignore the return value of a function, assign the returned value to std::ignore. Assigning to std::ignore clearly indicates developer intent and helps in future code maintenance.

#include <tuple>
#include <ctime>
#include <stdio.h>
void f()
{
    std::srand(static_cast(std::time(nullptr))); // set initial seed value to system clock
    std::ignore = std::rand(); // Discard the first result as the few random results are always small.
    // ... 
}

See also

fopen_s, _wfopen_s
Using SAL Annotations to reduce code defects