Possible Duplicate:
What is the size of void?
In §6.2.5.19, the prophets let us know that:
The
voidtype comprises an empty set of values
Then why does sizeof(void) yield 1, when 0 seems to suffice?
Possible Duplicate:
What is the size of void?
In §6.2.5.19, the prophets let us know that:
The
voidtype comprises an empty set of values
Then why does sizeof(void) yield 1, when 0 seems to suffice?
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
voidand on pointers to functions. This is done by treating the size of avoidor of a function as 1.A consequence of this is that
sizeofis also allowed onvoidand on function types, and returns 1.The option
-Wpointer-arithrequests 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).
sizeof(void) will not compile on a C compiler.
ISO 9899:2011 6.2.5/19
"The void type comprises an empty set of values; it is an incomplete object type that cannot be completed."
ISO 9899:2011 6.5.3.4/1
"The sizeof operator shall not be applied to an expression that has function type or an incomplete type"
This is normative text: sizeof(void) is not valid C.
You are probably using gcc, or some other compiler that does this as an extension (in C, sizeof(void) is not valid).
gcc says:
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.