Subscripting integer variable using a pointer

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[""]); /* What is x[""]?! */

    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.


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.


    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"];
    

    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]
    
    链接地址: http://www.djcxy.com/p/86726.html

    上一篇: 这个C ++代码是否产生未定义的行为?

    下一篇: 使用指针代替整数变量