Handmade Hero » Forums » Code » Fun with arrays in C
20 posts
1 project


#1639 Fun with arrays in C
2 years, 3 months ago

A funny little fact: - in C/C++ you can reverse array name and access index:

int arr[] = { 1, 2, 3 };
int x = arr[2]; // x == 3
int y = 2[arr]; // y == 3

I guess that's because behind the scene the compiler is replacing an array access with plain pointer arithmetic:

int z = *(arr + 2); //z == 3

Btw, my favorite C book is "Expert C Programming: Deep C Secrets" by Peter van der Linden (surprisingly the book is pretty funny too).

33 posts
#1708 Fun with arrays in C
2 years, 3 months ago

Sadly this is still valid C, even though this is only a remnant of the way the first compilers before standardization worked.

I hope nobody here thinks this would be a good idea and start using it.