7

Possible Duplicate:
What is the size of void?

Hi all ! I am using gcc for compiling my C programs, just discovered accidentally that the sizeof(void) is 1 byte in C.

Is there any explanation for this ? I always thought it to be ZERO (if it really stores nothing) !

Thanks !

Community
  • 1
  • 1
Raj
  • 91
  • 1
  • 1
  • 3
  • 1
    `void` has no size because `void` is an incomplete type. You cannot take the `sizeof` of an incomplete type. – GManNickG Jul 28 '10 at 07:11
  • If I try to create a SO-question with this title, I soon enough get a lot "related questions" around this very point... – pascal Jul 28 '10 at 07:13

3 Answers3

8

This is a non standard extension of gcc, but has a rationale. When you do pointer arithmetic adding or removing one unit means adding or removing the object pointed to size. Thus defining sizeof(void) as 1 helps defining void* as a pointer to byte (untyped memory address). Otherwise you would have surprising behaviors using pointer arithmetic like p+1 == p when p is void*.

The standard way would be to use `char* for that kind of purpose (pointer to byte).

kriss
  • 23,497
  • 17
  • 97
  • 116
2

this is a gcc specific feature - see here http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Pointer-Arith.html#Pointer-Arith

or

What is the size of void?

Community
  • 1
  • 1
Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61
1

Usually you don't ask for sizeof(void) since you never use void as type. I guess the behavior you are experimenting depends on the specific compiler. On my gcc it returns 1 as well.

Dacav
  • 13,590
  • 11
  • 60
  • 87