In C, if we have an array a :
unsigned char a[5];
Is the following expression :
a[3] == 3[a]
true or false, or its a syntax Error ?
It's true because of Pointer Arithmetic.
This is the direct artifact of arrays behaving as pointers, "a" is a memory address. "a[3]" is the value that's 3 elements further from "a". The address of this element is "a + 3".
This is equal to offset "a" from "3" elements at the beginning of the address space "3 + a".
Simpler, the C standard defines the [] operator as follows:
a[b] == *(a + b)
Therefore a[3] will evaluate to:
*(a + 3)
and 3[a] will evaluate to:
*(3 + a)
and this is why those are equal.
unsigned char a[5];
Is the following expression :
a[3] == 3[a]
true or false, or its a syntax Error ?
It's true because of Pointer Arithmetic.
This is the direct artifact of arrays behaving as pointers, "a" is a memory address. "a[3]" is the value that's 3 elements further from "a". The address of this element is "a + 3".
This is equal to offset "a" from "3" elements at the beginning of the address space "3 + a".
Simpler, the C standard defines the [] operator as follows:
a[b] == *(a + b)
Therefore a[3] will evaluate to:
*(a + 3)
and 3[a] will evaluate to:
*(3 + a)
and this is why those are equal.
No comments:
Post a Comment