Warning C6031

Return value ignored: 'called-function' could return unexpected value

Remarks

Warning C6031 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.

This warning applies to both C and C++ code.

Code analysis name: RETVAL_IGNORED_FUNC_COULD_FAIL

Example

The following code generates warning C6031:

#include <stdio.h>
int main()
{
    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>
int main()
{
    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>
int main()
{
    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()
{
    return true;
}

int main()
{
    func();
}

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

#include <sal.h>
_Check_return_ bool func()
{
    return true;
}

int main()
{
    if (func())
    {
        // code ...
    }
}

In cases where it's 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 <cstdlib>
#include <stdio.h>

int main()
{
    std::srand(static_cast<unsigned int>(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