Can I output a Windows handle using %p specifier?

sharptooth picture sharptooth · Jul 30, 2012 · Viewed 10k times · Source

This is a kind of follow-up to this question. Windows SDK features HANDLE datatype that is defined in WinNT.h as follows:

typedef void *HANDLE;

This datatype is used to represent handles. Technically a handle is not a pointer - it's magic value that can only be used with Win32 functions. Yet it is declared to be represented with a datatype that is a void* typedef.

If I want to output the handle hex value with the following code:

HANDLE handle = ...;
printf("%p", handle);

will it be legal?

Answer

Jonathan Potter picture Jonathan Potter · Jul 30, 2012

Yes it's fine, for two reasons. Firstly it is actually a pointer (a pointer to void), and secondly %p doesn't magically check that the value on the stack is a pointer - it just grabs the next pointer-sized value and prints it out.