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);
}
C arrays are declared in the following form: type name[number of elements]; For example, if we want an array of six integers (or whole numbers), we write in C: int numbers[6];
An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.
Arrays are always pass by reference in C. Any change made to the parameter containing the array will change the value of the original array. The ampersand used in the function prototype. To make a normal parameter into a pass by reference parameter, we use the "& param" notation.
An array reference variable is declared by the use of brackets.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With