Publications

of *Jon Jagger*

Appeared in CVu 8.6, Sept 1996

Addition is associative

There is a well known quirk in C that concerns the associativity of addition and arrays. The associativity of addition is a fancy way of saying that

a + b === b + a

The quirk revolves around the fact that given:

int a[16]; int i;

then:

a[i] === *(a + i)

Now, because the original designers of C decided to support the associativity of addition in this case, it is also true that:

a[i] === *(i + a)

which has the rather bizarre consequence that:

a[i] === i[a]

However things can get still more bizarre!

int a[16]; int b[16]; int i; assert( a[b[c]] == *(a + b[c]) ); assert( *(a + b[c]) == *(b[c] + a) ); assert( *(b[c] + a) == b[c][a] ); assert( b[c][a] == c[b][a] );

Hence:

assert( a[b[c]] == c[b][a] );

If your not convinced, try it:

#include <stdio.h> int main() { enum { limit = 8 }; int a[limit]; int b[limit]; int c; for (c = 0; c != limit; c++) { a[c] = b[c] = c; } for (c = 0; c != limit; c++) { printf("a[b[%d]] == %d\n, ", c, a[b[c]]); printf("b[%d][a] == %d\n, ", c, b[c][a]); printf("%d[b][a] == %d\n", c, c[b][a]); } return 0; }

That's all for now.

Cheers

*Jon Jagger*

jon@jaggersoft.com