I just ran into something very awkward while working with HRESULT return values, it seems that success is 0 and failure is 1. What is the logic behind this?
I actually tried if(!hr) and failed miserably, wasting an hour of my life until I figured out the actual success retval is 0. I would like to call the person who thought of this an idiot, but I’ll try to cool down – hoping someone will shed some light on this convention.
The original purpose of HRESULTs was to formally lay out ranges of error codes for both public and Microsoft internal use in order to prevent collisions between error codes in different subsystems of the OS/2 Operating System.
That’s why, value of 0 (of highest bit of HRESULT) means ‘no error’, that is, success.
But one should be careful, since it is possible for HRESULT to have highest bit set to 0 and other bits set different from 0. That means, the check
if(0 == hr) { ... }may not work for some successful cases. The correct way to check for success isif(0 <= hr) { ... }.Wikipedia has more detailed information.
SUCCEEDEDandFAILEDmacros can be used to avoid mistakes when dealing with HRESULT values.if(0 <= hr) { ... }andif(SUCCEEDED(hr)) { ... }are basically the same things.