简体   繁体   中英

Subtracting a value from a typedef in C?

I am reading some Windows API header files and I saw some code that I don't understand:

typedef void *HANDLE;

typedef HANDLE DPI_AWARENESS_CONTEXT;

#define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT)-1)

What does it mean to subtract a value from a void * typedef?

There's no subtraction going on - DPI_AWARENESS_CONTEXT_UNAWARE expands to the value of -1 cast as a void * . It appears that it's being used as a sentinel value for the DPI_AWARENESS_CONTEXT type (which is a typedef for HANDLE , which is a typedef for void * ).

It is a cast, not a subtraction.

typedef void *HANDLE;

Results in a symbol HANDLE that is equivalent to void *

Then in turn

typedef HANDLE DPI_AWARENESS_CONTEXT;

results in a new symbol DPI_AWARENESS_CONTEXT that is equivalent to void *

leading to the expression:

#define DPI_AWARENESS_CONTEXT_UNAWARE ((DPI_AWARENESS_CONTEXT)-1)

which is equivalent to:

#define DPI_AWARENESS_CONTEXT_UNAWARE ((void *)-1)

meaning that any instance of DPI_AWARENESS_CONTEXT_UNAWARE in source code expands to (void *) at compile-time.

As an aside - Here are the hows and whys:

(void *) -1 == (size_t) -1

which is 0xFFFFFFFF on 32 bit machines,
or 0xFFFFFFFFFFFFFFFF on 64 bit machines.

On twos complement implementations of each respective architecture, these values are equivalent to -1 , making them useful as sentinel values in routines such as sbrk()) (memory allocation support), or specifying dots per inch (dpi) awareness context .

Note : The above statement is incorrect for ones complement systems, but as indicated by the answers in this post ones complement is rare, and not likely to be used in any recent large scale commercial environment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM