Reputation: 3526
Below is a piece of code copied from a website. The value set for the direction prints the respective character from "nsew". For example the output of this code is character w.
I am wondering how does it work.
#include<stdio.h>
void main (void){
int direction = 3;
char direction_name = direction["nsew"];
printf("%c",direction_name);
}
Upvotes: 12
Views: 223
Reputation: 124642
This is because the array subscript operator is commutative, i.e., this:
const char *p = "Hello";
char x = p[0];
Is equivalent to
const char *p = "Hello";
char x = 0[p];
Weird, huh? In your case you are indexing into the third position of the string literal (which is an array) "nsew"
.
some_ptr[n]
is equivalent to *(some_ptr + n)
, and since addition is commutative, it is also equivalent to *(n + some_ptr)
. It then follows that n[some_ptr]
is also an equivalent expression.
I wouldn't recommend using this "feature" however... seriously, don't do it.
Upvotes: 17
Reputation: 9089
Operator []
has the same semantics as pointer arithmetics. So a[i]
is equivalent to *(a + i)
which is equivalent to *(i + a)
which is equivalent to i[a]
:
So direction["nsew"]
== "nsew"[direction]
== "nsew"[3]
== 'w'
Upvotes: 8