15

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?

Coder_Dan
  • 1,815
  • 3
  • 23
  • 31
  • Handles aren't pointers, but indexes to a table. Consult MSDN for return values. And anyway, why `if (x){..` isn't good? – ruslik Oct 11 '10 at 10:59
  • 1
    Thanks for this one - call me old-fashioned, but I normally reserve the 'if (x)' notation for expressions that evaluate to 'bool' results. I don't know whether this is good or bad practice, but it's what I'm used to. – Coder_Dan Oct 12 '10 at 12:39

3 Answers3

10

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).

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • 2
    Thanks for that answer - I guess you're right, there's not a lot of consistency and I should just do what the MSDN tells me. – Coder_Dan Oct 12 '10 at 12:35
3

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.

Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
1

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

sje397
  • 41,293
  • 8
  • 87
  • 103
  • 4
    Thats not always true. It depends on what API you are calling ... which is a HUGE pain :( – Goz Oct 11 '10 at 11:30
  • 1
    If you do: `HWND hwnd = INVALID_HANDLE_VALUE` you get a compile time error. Which seems odd to me. – mike jones Feb 13 '13 at 18:27