Search code examples
carraysstringstring-literalsc89

Index operator bound to a string literal


So I decided to experiment, completely out of randomness. And I found this:

"Hello World"[1]

Actually working on a first view, resulting in 'e' even though:

  • I haven't encounter this anywhere until happened to be in my code
  • Seems semantically controversial (or at least quite suspicious)
  • Could not find any information on the internet, regarding this positive string literal array indexing (probably searching in the wrong context?)

Is this actually allowed, confronting the "standards" with guaranteed well-defined behavior ?


Solution

  • This is semantically correct. "Hello World"[1] is equivalent to *("Hello World" + 1). In this expression the string "Hello World" will be converted to pointer to its first element. Therefore, ("Hello World" + 1) is the address of second element of string "Hello World".