Syntactic sugar in C: accessing arrays

Arrays in C are very easy to use, and that’s mostly because of the implementation behind the scenes. One of the things that makes this extremely clear, is the following line of code:

a[10] == 10[a]

This is always true, because C uses what is called syntactic sugar. This isn’t a real concept, but rather a name for syntax that makes a programming language sweeter to humans. This expression was coined for the first time by the computer scientist Peter John Landin, to express easy syntax to make programming easier.

Not everyone likes the term syntactic sugar. One of them is Jen Chan, who wrote a shitpost about it, calling almost everything in a programming language sugar. Perhaps he is right about that, but there are a few things that clearly are sweeter than others.

The best example in C is without a doubt a[10] == 10[a]. This can be tested with simple code like this:

int a[20];
if (a[10] == 10[a])
	printf("These are equal!\n");

This will print These are equal!. The reason for this is fairly simple: this syntax is only meant to hide the real syntax for accessing:

a[10] = *(a + 10)

Sadly, all good things must have a downside. The downside of this sugar, is that the compiler is unable to validate the left hand side of this expression. Because of this, this is also an option:

10[a] = *(10 + a)

Thankfully, that does not matter, because the operation is commutative. That means that the order of addition is not relevant to the output.

Leave a Reply

Your email address will not be published. Required fields are marked *