Dela via


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.

Example

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 MustCheck property as shown in the following code:

#include <codeanalysis\sourceannotations.h>
[returnvalue:SA_Post(MustCheck=SA_Yes)] bool func( );

void test_f()

{

func( ); //return value ignored

}

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

void test_f()

{

if( func( ) )

{

//code...

}

}

See Also

Reference

fopen_s, _wfopen_s

MustCheck

Concepts

Annotation Overview