bubble
bubble

Reputation: 3526

Why does this C array reference look incorrect?

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

Answers (2)

Ed Swangren
Ed Swangren

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

Rost
Rost

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

Related Questions