Have You Ever Seen Code Like This?

emmtrix Tech Posts
Category: C Code

What does this program do?

  1. Compiler error
  2. Output 3
  3. Output 2
  4. Segmentation fault

Ever seen code like this?
Today our whole team stopped its tracks when we ran across this little-known corner case of the C language – none of us had ever met it in the wild, and it blew our minds.

Play with it yourself on Compiler Explorer

Why it works?

1. Subsript symmetry
In C, a[b] is defined as * (a + b). Because addition is commutative, b[a] is exactly the same as a[b].

2. Un-rolling the expression

Step

Expression

Meaning

1

1 [A]

same as A[1] = the second row {3,4}

2

0 [1 [A] ]

Same as (1 [A]) [0] = first element of that row

3. Value produced
A[1] [0] equals 3, so the program prints 3 (Option B).

Take-away?
This isn’t a trick of undefined behavior; it’s 100% standard-conformant C, hiding in plain sight. Although you can write code like this, you probably shouldn’t – readability matters!

But knowing the rule keeps you safe when you encounter auto-generated or deeply macro-fied code.

Engineering update
We discovered that our C source-to-source compiler didn’t recognize this construct properly. A fix is already in the pipeline, and full support will ship tomorrow across the entire toolchain powering our products.

Stay tuned!

Cookie Consent with Real Cookie Banner