Quick Q: With arrays, why is it the case that a[5] == 5[a]?

Quick A: See below

Recently on SO:

With arrays, why is it the case that a[5] == 5[a]?

The C standard defines the [] operator as follows:

a[b] == *(a + b)

Therefore a[5] will evaluate to:

*(a + 5)

and 5[a] will evaluate to:

*(5 + a)

a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).

Add a Comment

Comments are closed.

Comments (1)

0 0

casenet said on Jun 14, 2019 03:11 AM:



The C standard defines the [] operator as follows:

a[b] == *(a + b)

Therefore a[5] will evaluate to:

*(a + 5)

and 5[a] will evaluate to:

*(5 + a)

a is a pointer to the first element of the array. a[5] is the value that's 5 elements further from a, which is the same as *(a + 5), and from elementary school math we know those are equal (addition is commutative).[url="https://wp.me/aZ4zD" rel="dofollow"]Casenet[/url]