Edit

Share via


Warning C6217

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

Remarks

This warning indicates that the code tests an HRESULT with the logical-not (!) operator. A value of 0 (the value defined for S_OK) indicates success in an HRESULT. However, 0 also indicates failure for a Boolean type. If you test an HRESULT with the logical-not operator (!) to determine which code block to run, it can cause incorrect behavior or code that confuses future maintainers.

To verify whether an HRESULT is a success or failure, use the SUCCEEDED or FAILED macros instead.

This warning works for both HRESULT and SCODE types.

Code analysis name: TESTING_HRESULT_WITH_NOT

Example

The following code generates this warning because it uses the logical-not (!) operator to determine success or failure of an HRESULT value. In this case, the code executes the wrong code path because an HRESULT of 0 indicates success, so ( !hr ) incorrectly 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 a FAILED macro to check for failure:

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

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

See also

SUCCEEDED macro
FAILED macro