Why does the below code not generate an error and print the value stored in arr then followed by a junk value ?
int main() {
int arr[1]={10};
printf("%d %d\n",0[arr], 1[arr] );
return 0;
}
Why does the below code not generate an error and print the value stored in arr then followed by a junk value ?
int main() {
int arr[1]={10};
printf("%d %d\n",0[arr], 1[arr] );
return 0;
}
In C, 0[arr] == arr[0]
.
So,
0[arr]==arr[0]==10.
and
1[arr]==arr[1]==Junk value
Check this SO question and it's answers.
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) and from elementary school math we know those are equal. (Addition is commutative.)
This is the direct artifact of arrays behaving as pointers, "a" is a memory address. "a[5]" is the value that's 5 elements further from "a". The address of this element is "a + 5". This is equal to offset "a" from "5" elements at the beginning of the address space (5 + a).
1[arr]
is the same as arr[1]
.
This is possible because E1[E2]
is equivalent to (*((E1) + (E2))
in C by definition of []
operator.
Note that if you declare:
int arr[1]={10};
There is only element in the array, arr[0]
and there is no arr[1]
element.