Josh
Josh

Reputation: 43

Why is void pointer arithmetic allowed in gcc?

The following code is compiling using gcc although void ptr arithmetic is not standard:

int main(){
 int a = 5;
 void* b = (void*) &a;
 b++;
}

Upvotes: 4

Views: 348

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

This is explained by the fact that initially there was not the type void in C. Instead of it the type char played its role. And sizeof( char ) is equal to 1.

For example I saw a very old legacy code where there was written

memset( ( char * )p, 0, n );

where the argument p has the type int *.

So it seems this was done for backward compatibility.

Upvotes: -2

dbush
dbush

Reputation: 224577

This is an extension supported by GCC. It treats a void * like a char *.

From the gcc docs:

6.24 Arithmetic on void- and Function-Pointers

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.

Upvotes: 5

Related Questions