Weird way to print array

Jun 28, 2013 at 4:46pm
I was helping someone else on this forum, and made a mistake in my for loop, but to my amazement, it still printed out the array. Could someone explain WHY this works, when there is NO array named i?

I try searching google, and other sites, but do not find any reference to this way of programming.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Loop.cpp : main project file.

#include <iostream>
#include <string>

using namespace std;


int main()
{
	string question[8]={"Why","does","this","work","with","NO","errors", "?"};
	
	for (int i=0; i<8; i++)
		cout << i[question] << " ";
		// Don't really understand WHY this works correctly. Should be question[i]
	
	cout << endl << endl;
	
	return 0;
}
Jun 28, 2013 at 5:00pm
closed account (Dy7SLyTq)
ummmmm.... is it a c++ 11 thing? does it work because of the range based for loop?
Jun 28, 2013 at 5:31pm
ummmmm.... is it a c++ 11 thing?


No. It's a since-the-beginning type of thing.

question[i] is the same as *(question+i).

i[question] is the same as *(i+question).

*(question+i) and *(i+question) are the same thing.
Jun 28, 2013 at 6:15pm
@cire

Thanks for the info. I've never seen a loop being done any other way, except by what show in books as is a normal loop. And, judging by DTSCode's response, I'm not alone. I will make sure to add this styling to my repertoire. My thanks again.
Jun 28, 2013 at 7:37pm
To make cire's response more readable:

In C (and hence C++), it is legal to write:

7[myarray]

instead of

myarray[7]

They both mean the same thing.


That said, don't. No one will like you if you do.
Jun 28, 2013 at 10:56pm
closed account (Dy7SLyTq)
wow... c shocks me again.
Jun 28, 2013 at 11:23pm
No one will like you if you do.


Just remember this.
Jun 29, 2013 at 2:34am
No one will like you if you do.


Just remember this.

Wow. I guess this is something I better NOT forget. Okay, I'll stick to the traditional way of using the for loop. Thanks to you all for helping me understand this, and helping me with traditional, and easier to understand, C++.
Topic archived. No new replies allowed.