HRESULT

HRESULT is a 32‑bit value used in Windows programming to indicate the success or failure of an operation. It combines severity, facility, and status code information in a single integer.

Structure of an HRESULT

 31   30   29-16            15-0
 ──────┬─────┬───────────────┬───────
|Severity|C|  Facility   | Code   |
 ──────┴─────┴───────────────┴───────

Common Macros

#define SUCCEEDED(hr) (((HRESULT)(hr)) >= 0)
#define FAILED(hr)    (((HRESULT)(hr)) < 0)

#define HRESULT_CODE(hr)    ((hr) & 0xFFFF)
#define HRESULT_FACILITY(hr) (((hr) >> 16) & 0x1FFF)
#define HRESULT_SEVERITY(hr) (((hr) >> 31) & 0x1)

Typical HRESULT Values

ValueNameDescription
0x00000000S_OKOperation successful.
0x80004005E_FAILUnspecified failure.
0x80070005E_ACCESSDENIEDGeneral access denied error.
0x80070057E_INVALIDARGOne or more arguments are invalid.
0x80040154REGDB_E_CLASSNOTREGClass not registered.

Using HRESULT in Code

#include <windows.h>

HRESULT DoSomething()
{
    // Some operation
    if (/* success */) return S_OK;
    return E_FAIL;
}

int main()
{
    HRESULT hr = DoSomething();
    if (SUCCEEDED(hr)) {
        // success path
    } else {
        // error handling
        DWORD winErr = HRESULT_CODE(hr);
        // translate winErr, log, etc.
    }
    return 0;
}