5

Possible Duplicate:
In C arrays why is this true? a[5] == 5[a]

3["zdvnngfgnfg"];

Community
  • 1
  • 1
StevenWang
  • 3,625
  • 4
  • 30
  • 40
  • 3
    Checkout http://stackoverflow.com/questions/381542/in-c-arrays-why-is-this-true-a5-5a/381549#381549 as well – Daff Sep 21 '09 at 09:46

3 Answers3

9

It's equivalent to

"zdvnngfgnfg"[3];

which is legal and means "take the address of that literal and add 3*sizeof(char) to it". Will have no effect anyway.

Also see this very similar question.

Community
  • 1
  • 1
sharptooth
  • 167,383
  • 100
  • 513
  • 979
  • 1
    Doesn't the meaning also include "and then fetch the value at that address"? – unwind Sep 21 '09 at 11:34
  • I suppose no, since the statement is neither on the left nor on the right side of the assignment. – sharptooth Sep 21 '09 at 11:47
  • 1
    Since the snippet is a full expression, it does in fact mean "and then fetch the value". But because doing so has no defined side-effects, and the result is discarded, the compiler is allowed to omit it. In fact the compiler will probably omit the pointer addition as well - all it will do is make sure the statement is legal, realise it does nothing, and elide it. Certainly that's what gcc does, even with no optimisation. – Steve Jessop Sep 21 '09 at 11:59
  • In C, an expression that appears as an expression statement is converted to an rvalue: The value therein is accessed. "Except when it is the operand of the sizeof operator, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object". The behavior is different from C++, in which no value is fetched if the read wasn't requested. But surely, you won't notice the difference since the array isn't volatile :) – Johannes Schaub - litb Sep 21 '09 at 15:05
  • Indexing a constant string makes for especially nice-looking code when used to convert to a hexadecimal digit: char digit = "0123456789ABCDEF"[i]; – Heath Hunnicutt Oct 16 '09 at 09:55
6

arr[i] is parsed as *(arr+i) which can be written as *(i+arr) and hence i[arr]
Now "strngjwdgd" is a pointer to a constant character array stored at read only location.
so it works!!

sud03r
  • 19,109
  • 16
  • 77
  • 96
2

The string literal(array) decays to a pointer of type char*. Then you take the fourth element:

3["zdvnngfgnfg"] == "zdvnngfgnfg"[3]

Why you can write the subscript infront of the array is another question:

In C arrays why is this true?

Community
  • 1
  • 1
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234