Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Implicit cast between semantically different integer types: comparing HRESULT to an integer. Consider using
SUCCEEDED
orFAILED
macros instead
This warning indicates that an HRESULT
is being compared to an integer other than zero.
Remarks
A success in an HRESULT
(S_OK
) is represented by a 0. Therefore, an implicit cast of an HRESULT
to an integer generates an incorrect value and is likely to lead to the wrong result. The error is often caused by mistakenly expecting a function to return an integer when it actually returns an HRESULT
.
Code analysis name: COMPARING_HRESULT_TO_INT
Example
The following code generates warning C6221 by comparing an HRESULT
against an integer value:
#include <windows.h>
HRESULT f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if (hr == 4)
{
// failure code ...
return S_FALSE;
}
else
{
// success code ...
return S_OK;
}
}
To correct this warning, the following code uses the FAILED
macro:
#include <windows.h>
HRESULT f( )
{
HRESULT hr;
LPMALLOC pMalloc;
hr = CoGetMalloc(1, &pMalloc);
if (FAILED(hr))
{
// failure code ...
return S_FALSE;
}
else
{
// success code ...
return S_OK;
}
}
For this warning, the SCODE
type is equivalent to HRESULT
.
For more information, see SUCCEEDED
Macro and FAILED
Macro.
The use of malloc
and free
(and related dynamic memory allocation APIs) has many pitfalls in terms of memory leaks and exceptions. To avoid these kinds of potential leaks altogether, use the mechanisms that are provided by the C++ Standard Library (STL). These include shared_ptr
, unique_ptr
, and containers such as vector
. For more information, see Smart pointers and C++ Standard Library.