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 |
──────┴─────┴───────────────┴───────
- Severity (bit 31) – 0 = success, 1 = failure.
- C (bit 30) – Reserved (used for Microsoft extensions).
- Facility (bits 29‑16) – Origin of the error (e.g.,
FACILITY_WIN32
). - Code (bits 15‑0) – Specific error or status 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
Value | Name | Description |
---|---|---|
0x00000000 | S_OK | Operation successful. |
0x80004005 | E_FAIL | Unspecified failure. |
0x80070005 | E_ACCESSDENIED | General access denied error. |
0x80070057 | E_INVALIDARG | One or more arguments are invalid. |
0x80040154 | REGDB_E_CLASSNOTREG | Class 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;
}