C/C++ is sometimes considered the mid-level programming language because if offers the powerful pointers. We know that, like many other programming languages, if you have a array named arr to access the fifth element, the notation is arr[4] (zero index). This is very straightforward and easy to understand. In C/C++ you can write it the other way, which is 4[arr].
Don’t believe this? Try the following simple C program and it will work.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #include <stdio.h> #include <string.h> int main() { int a[10]; const int N = 10; for (int i = 0; i < N; i ++) i[a] = i; for (int i = 0; i < N; i ++) printf("%d", i[a]); char s[100]; strcpy(s, "Hello, World!"); for (int i = 0; i < strlen(s); i ++) printf("%c", i[s]); return 0; } |
#include <stdio.h> #include <string.h> int main() { int a[10]; const int N = 10; for (int i = 0; i < N; i ++) i[a] = i; for (int i = 0; i < N; i ++) printf("%d", i[a]); char s[100]; strcpy(s, "Hello, World!"); for (int i = 0; i < strlen(s); i ++) printf("%c", i[s]); return 0; }
This prints the following as expected.
0123456789Hello, World!
So, the question is why this works? Well, in fact, the notation a[i] is translated to *(a + i) which is the same as *(i + a). The latter is the i[a]. The array accesses are translated into pointers. The address of the element to access will be calculated.
However, this kind of notation just serves to understand the array/pointer better, I would not recommend this syntax as the first one is much more straightforward.
–EOF (The Ultimate Computing & Technology Blog) —
Last Post: Tutorial: How to Write a Java Date Class (Basic OOP Concept)
Next Post: Getting the Source File Name and Line Number using __FILE__ and __LINE__ compiler constants in C/C++