Why is the windows return code called HRESULT?

3.6k views Asked by At

The standard return type for functions in Windows C/C++ APIs is called HRESULT.

What does the H mean?

4

There are 4 answers

0
Carl Norum On

The documentation only says:

The return value of COM functions and methods is an HRESULT, which is not a handle to an object, but is a 32-bit value with several fields encoded in a single 32-bit ULONG variable.

Which seems to indicate that it stands for "handle", but is misused in this case.

0
StarPilot On

Hex Result.

HRESULT are listed in the form of 0x80070005. They are a number that gets returned by COM\OLE calls to indicate various types of SUCCESS or FAILURE. The code itself is comprised of a bit field structure for those that want to delve into the details.

Details of the bit field structure can be found here at Microsoft Dev Center's topic Structure of COM Error Codes and here at MSDN HRESULT Structure.

0
franckspike On

Result handle as stated here at MSDN Error Handling in COM

0
IInspectable On

The H-prefix in Windows data types generally designates handle types1 (such as HBRUSH or HWND). The documentation seems to be in agreement, sort of:

The HRESULT (for result handle) is a way of returning success, warning, and error values. HRESULTs are really not handles to anything; they are only values with several fields encoded in the value.

In other words: Result handles are really not handles to anything. Clearly, things cannot possibly have been designed to be this confusing. There must be something else going on here.

Luckily, historian Raymond Chen is incessantly conserving this kind of knowledge. In the entry aptly titled Why does HRESULT begin with H when it’s not a handle to anything? he writes:

As I understand it, in the old days it really was a handle to an object that contained rich error information. For example, if the error was a cascade error, it had a link to the previous error. From the result handle, you could extract the full history of the error, from its origination, through all the functions that propagated or transformed it, until it finally reached you.

The document concludes with the following:

The COM team decided that the cost/benefit simply wasn’t worth it, so the HRESULT turned into a simple number. But the name stuck.

In summary: HRESULT values used to be handle types, but aren't handle types any more. The entire information is now encoded in the value itself.


Bonus reading:

Handle types losing their reference semantics over time is not without precedent. What is the difference between HINSTANCE and HMODULE? covers another prominent example.


1 Handle types store values where the actual value isn't meaningful by itself; it serves as a reference to other data that's private to the implementation.