Coder_Dan
Coder_Dan

Reputation: 1882

Testing for an invalid windows handle: should I compare with 'NULL', '0' or even 'nullptr'?

I'm coming from a background whereby pointers should generally be compared with 'NULL' and integers with '0'.

Since I didn't perceive Windows handles to be 'pointers' in the pure sense (being 'handles'), I'd got into the habit of comparing them with 0 rather than 'NULL'.

Clearly they're implemented internally as pointers nowadays, but I personally consider that to be merely for acquiring some type-safety rather than because they are intrinsically pointers.

Anyway, I just noticed that the help for CreateIC which returns an HDC states that if the function fails then it returns 'NULL'.

Now I'm confused - and am wondering what other people reckon - is it more correct to consider a Windows handle to be a pointer (and therefore check it against 'NULL' or 'nullptr' for modern compilers) or should it be considered to be an integer?

Upvotes: 16

Views: 12145

Answers (3)

MSalters
MSalters

Reputation: 179981

Compare it against the documented error return value. That means that you should compare it against INVALID_HANDLE, 0, -1, non-zero, or <=32 (I'm not kidding with the last one, see ShellExecute).

Upvotes: 12

Frerich Raabe
Frerich Raabe

Reputation: 94409

To answer your question: the HANDLE type is declared in winnt.h as

typedef PVOID HANDLE;

Hence, technically it is a pointer.

However, I would just use whatever is documented; if the documentation states that NULL is returned, I use exactly that unless evidence shows that the documentation is incorrect.

I don't even think about pointers vs. integers. NULL is just an opaque value (in this situation) and HANDLE is an opaque type to me and I don't bother looking up what it is #define'd to.

Upvotes: 3

sje397
sje397

Reputation: 41852

I think INVALID_HANDLE_VALUE is usually the proper 'invalid' value for windows handles...and that evaluates to -1.

Upvotes: 0

Related Questions