Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer indexed with a string in c++ [duplicate]

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

How is it possible that this is valid C++?

void main()
{
  int x = 1["WTF?"];
}

On VC++10 this compiles and in debug mode the value of x is 84 after the statement.

What's going on?

like image 245
ehremo Avatar asked Jan 17 '13 12:01

ehremo


1 Answers

Array subscript operator is commutative. It's equivalent to int x = "WTF?"[1]; Here, "WTF?" is an array of 5 chars (it includes null terminator), and [1] gives us the second char, which is 'T' - implicitly converted to int it gives value 84.

Offtopic: The code snippet isn't valid C++, actually - main must return int.

You can read more in-depth discussion here: In C arrays why is this true? a[5] == 5[a]

like image 199
jrok Avatar answered Oct 06 '22 22:10

jrok