rph
rph

Reputation: 911

Is GCC's "void pointer arithmetic" deterministic?

I've come across a C++ library that had the following code:

void *data;
unsigned length;
...
addr = data + length

First, it does not make much sense to use void* arithmetics since the compiler will not know what is the "size" of each element (as better explained here: void * arithmetic).

However, since I've used the library with my code and it seems to work, I was wondering the following. Is this behavior deterministic in the sense that all GCC will generate the same code everytime? Or, will GCC optimize it in a heuristic way?

Upvotes: 2

Views: 127

Answers (1)

Bathsheba
Bathsheba

Reputation: 234825

The behaviour of pointer arithmetic on a void* pointer is undefined.

GCC allows it as a non-standard compiler extension (essentially regarding void* as a char* for purposes of pointer arithmetic).

Upvotes: 7

Related Questions