简体   繁体   中英

Complex Declaration of Sizeof operator in C

I have seen this complex declaration of sizeof operator somewhere in book which is teasing me:

#define SIZEOF(int)  (int)&((int *)0)[1]

Can any one explain this declaration, whats going on here...?

Here it is with the [1] part 'expanded':

(int)(&(*(((int*)0) + 1)))

Now do you see how it works?

The 0 will increase by the sizeof int due to the properties of pointer arithmetic and the final int cast is getting you the value of the resulting address which is the 'size'.

It's totally undefined behavior though (the arithmetic on null and possibly the dereference of invalid pointer), fairly pointless.


The update with the macro parameter doesn't make much sense. The final cast should probably be std::uintptr_t .

First -- it's confusing things with the term int -- we naturally assume that to be the keyword of a familiar type, however in this case it's not -- instead, it's the argument to the macro. So to simplify, consider the macro as follows:

#define SIZEOF(type)  &((type *)0)[1]

Now looking at it this way, it's perhaps easier to see that the macro is first casting address 0 to be a pointer to type , and then it's taking the address of the second element. This will reveal the size.

It defines SIZEOF as the size of an integer.

  • (int *)0 is an int pointer at address zero
  • [1] accesses the next integer after that one.
  • Since (int *)0 has the address zero, the one after it has the address sizeof int as it comes right after the previous one.
  • (int) casts it to a number since a size is a number, not a pointer.

Obviously it's a nasty hack, one should simply use sizeof int .

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