C pointer arithmetic weirdness

Here’s an interesting example of the uniformity inherent to C pointer arithmetic and vector indexing. Will this piece of code work?

int v[10]; //let's assume it is initialized
int elem = 3[v];

It turns out that yes, it’s valid code. Any good C compiler (like GCC) should accept this. This is explained with a set of equalities:

v[3] == *(v + 3) == *(3 + v) == 3[v]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: