Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sizeof(void) == 1? [duplicate]

Tags:

c

gcc

Possible Duplicate:
What is the size of void?

In §6.2.5.19, the prophets let us know that:

The void type comprises an empty set of values

Then why does sizeof(void) yield 1, when 0 seems to suffice?

like image 294
Philip Avatar asked May 11 '12 12:05

Philip


1 Answers

It is a gcc extension: http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Pointer-Arith.html#Pointer-Arith

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

A consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

The option -Wpointer-arith requests a warning if these extensions are used.

The reason why void needs a size to perform such arithmetics is that ptr - ptr2 does not actually gives you the numeric difference of the addresses but the number of elements the two pointers are apart - and the size of an element pointed to by void *ptr is sizeof(*ptr) which is sizeof(void).

like image 76
ThiefMaster Avatar answered Sep 28 '22 09:09

ThiefMaster