Is there any justification for addressing array like <number>[array]?

I have never encountered this in "real code" (i.e., outside of intentionally obfuscated things and puzzles with artificial limitations) so it would seem that it is quite universally agreed that this shouldn't be done.

However, I can come up with a contrived example where it might be considered by some (not necessarily me) a nicer syntax: if you have multiple pieces of data related to a single entity in a column, and you represent the rows as different arrays:

enum { ADA, BRIAN, CLAIRE };
const char *name[] = { "Ada", "Brian", "Claire" };
const unsigned age[] = { 30, 77, 41 };

printf("%s is %u years old\n", ADA[name], ADA[age]);

I will be the first to agree that this obfuscates the syntax by making it look like the people are the arrays instead of being the indexes, and I would prefer an array of struct in most cases. I think a case could be made for this being nicer-looking, though, or perhaps in some cases it would be a way to swap the rows and columns (arrays and indexes) with minimal edits elsewhere.


As far as I can tell, there are no technical pros or cons with either method. They are 100% equivalent. As the link you provided says, a[i] = *(p+i) = [addition is commutative] = *(i+p) = i[a].

For subjective pros and cons, well it's confusing. So the form index[array] is useful for code obfuscation, but other than that I cannot see any use of it at all.

One reason (but I'm really digging here) to use the standard way is that a[b+c] is not equivalent to b+c[a]. You would have to write (b+c)[a] instead to make it equivalent. This can be especially important in macros. Macros usually have parenthesis around every single argument in every single usage for this particular reason.

It's basically the same argument as to write if(2==x) instead of if(x==2). If you by accident write = instead of == you will get a compiler error with the first method.

Can I continue with my life without worrying?

Yes.


Yes, the pointer arithmetic is commutative because addition is commutative. References like a[n] are converted to *(a+n) but also n[a] is converted to *(n+a), which is identical. If you want to win ioccc competitions you must use this.

Tags:

C