Export (0) Print
Expand All
Expand Minimize

C6031

warning C6031: return value ignored: <function> could return unexpected value

This warning indicates that the calling function is not checking the return value of a function call that signals failure via its return value. Depending on which function is being called, this defect can lead to seemingly random program misbehavior, including crashes and data corruptions in error conditions or low-resource situations.

In general, it is not safe to assume that a call to function requiring disk, network, memory, or other resources will always 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.

The following code generates this warning:

#include <stdio.h>
void f( )
{
  fopen( "test.c", "r" ); // 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 …
    }
}
Show:
© 2014 Microsoft