As Joel points out in Stack Overflow podcast #34, in C Programming Language (aka: K & R), there is mention of this property of arrays in C: a[5] == 5[a]
Joel says that it's because of pointer arithmetic but I still don't understand. Why does a[5] == 5[a]
?
In C arrays,
arr[3]
and3[arr]
are the same, and their equivalent pointer notations are*(arr + 3)
to*(3 + arr)
. But on the contrary[arr]3
or[3]arr
is not correct and will result into syntax error, as(arr + 3)*
and(3 + arr)*
are not valid expressions. The reason is dereference operator should be placed before the address yielded by the expression, not after the address.For pointers in C, we have
and also
Hence it is true that
a[5] == 5[a].
One thing no-one seems to have mentioned about Dinah's problem with
sizeof
:You can only add an integer to a pointer, you can't add two pointers together. That way when adding a pointer to an integer, or an integer to a pointer, the compiler always knows which bit has a size that needs to be taken into account.
in c compiler
are different ways to refer to an element in an array ! (NOT AT ALL WEIRD)
In C
Pointer is a "variable"
array name is a "mnemonic" or "synonym"
p++;
is valid buta++
is invalida[2]
is equals to 2[a] because the internal operation on both of this is"Pointer Arithmetic" internally calculated as
*(a+3)
equals*(3+a)
To answer the question literally. It is not always true that
x == x
prints