Udostępnij za pośrednictwem


C6217

warning C6217: Implicit cast between semantically different integer types: testing HRESULT with 'not'. Consider using SUCCEEDED or FAILED macro instead

This warning indicates that an HRESULT is being tested with the not (!) operator. A success (S_OK) in HRESULT is indicated by a value of 0. However, 0 indicates failure for a Boolean type. Testing HRESULT with the not operator (!) to determine which code block to run can cause following the wrong code path. This will lead to unwanted results.

Example

The following code generates this warning because the not operator is used to determine success or failure of an HRESULT value. In this case, wrong code path is executed because ( !hr ) runs the failure code:

#include <windows.h>
#include <objbase.h>

void f( )
{
  HRESULT hr = CoInitialize(NULL); 
  if (!hr)
  {
    // failure code ...
  }
  else
  {
    // success code ...
  }
}

To correct this warning, the following code uses FAILED macro to look for failure:

#include <windows.h>
#include <objbase.h>

void f( )
{
  HRESULT hr = CoInitialize(NULL);  
  if (FAILED(hr))
  {
    // failure code ...
  }
  else
  {
    // success code ...
  }
}

For this warning, the SCODE type is equivalent to HRESULT.

The typical success value of HRESULT (S_OK)is false when it is tested as a Boolean.

To verify whether HRESULT is a success, use the SUCCEEDED macro instead.

See Also

Other Resources

SUCCEEDED

FAILED