3

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]
C weird array syntax in multi-dimensional arrays

Today I came across this blog. What attracted me the most is this:

int i;
i["]<i;++i){--i;}"];

Well, I don't really know what is the purpose of the weird "string constant" inside the array subscript, but I am confused how it is possible to subscript an integer variable. So I came with this code:

#include <stdio.h>

int main(void) {
    int x = 10;

    printf("%d", x["\0"]); /* What is x["\0"]?! */

    return 0;

}

It compiles without error using MinGW with -Wall -ansi -pedantic. This code then outputs: 105.

Can anyone interpret this?

Edit: I found that there must be a pointer inside the subscript, or else I get compile-time error.

0

3 Answers 3

5

It's a consequence of how array indexing works:

Given an array:

int array[5];

then

array[3]

is really just another syntax for

*(array + 3)

Consequently that is the same as

*(3 + array)

Which means you also can do

3[array]
5

The C11 standard says this:

6.5.2.1, Array Subscripting

[...]

A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

Note:

E1[E2] is identical to (*((E1)+(E2)))

therefore

 E1[E2] = E2[E1]

. Furthermore,

6.4.5 String Literals

[...]

The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. For character string literals, the array elements have type char

so it is valid to do the following:

"foobar"[x];
x["foobar"];
4

It's a well-known trick. Because of the way pointer arithmetic works, the following are synonymous:

  • v[5]
  • 5[v]
  • *(v + 5)

It's the same thing when v happens to be a string literal.

3
  • 2
    Well, strictly speaking, this is possible not by the nature of pointer arithmetics, but due to the peculiarity of language standard. The standard could as well disable indexing an int with an array without any practical loss for the language.
    – Vlad
    Jul 5, 2012 at 13:56
  • 1
    I am not sure about it being "well known", tho Jul 5, 2012 at 14:01
  • @nos: yes. But other languages define indexing in a "more type-friendly way", requiring exactly the variable being indexed (and not the index) to be an array. For C, the addition has a special meaning when only one of the operands is an array, this is quite peculiar.
    – Vlad
    Jul 5, 2012 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.