Accessing an Array in C++

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream.h>
#include <stdio.h>
#include <conio.h>

void main()
{
	int a[10] = {1,3, 5, 7, 9, 11, 13, 15, 17, 19};

	printf("%d", 5[a]);

	getch();
}



11


In the above code I have accessed the array as 5[a] rather than a[5]. The code on compilation does NOT generate any error and executes successfully and generates the output 11, which is the element at the 5th position in the array.

Actually this code was given to me by a student, which she found in some programming book. At first I thought, this contains an error, but surprisingly worked fine. Myself and my student are wonder-struck with this code, because both of us don't have an explanation for this behaviour. Can anyone help us !

Thanks In Advance!
Gnanavel S
I too found this really weird at first..
This is what the standard has to say about this:
A postfix expression followed by an expression in square brackets is a postfix expression. One of the
expressions shall have the type “pointer to T” and the other shall have enumeration or integral type. The
result is an lvalue of type “T.” The type “T” shall be a completely-defined object type.56) The expression
E1[E2] is identical (by definition) to *((E1)+(E2)). [Note: see 5.3 and 5.7 for details of * and + and
8.3.4 for details of arrays. ]
In words of fewer syllables for our readers whose first language is not English (I've learned by experience that the standard is not kind to such readers!)

a[5] becomes *(a+5) where a is a pointer

5[a] becomes *(5+a)

and of course, in pointer addition, a+5 and 5+a are evaluated to the same result.
Thank you guys, I got it !
Topic archived. No new replies allowed.