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

None

#1639 Fun with arrays in C
2 years, 5 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).
http://www.amazon.com/Expert-Prog...ng-Peter-van-Linden/dp/0131774298

None
5sw
Sven
33 posts
#1708 Fun with arrays in C
2 years, 5 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.