
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
An Uncommon representation of array elements in C++ program
In this article, we will learn an uncommon representation of array elements in both C and C++.
Example of Uncommon Representation of Array Elements
Consider following code in C/C++, that is trying to print an element from an array.
#include <stdio.h> int main() { int arr[2] = {0,1}; printf("First Element = %d\n",0[arr]); }
Output
The output of above program will be:
First Element = 0
#include <iostream> using namespace std; int main() { int arr[2] = {0,1}; cout << "First Element = " << 0[arr] << endl; }
Output
The output of above program will be:
First Element = 0
In the above code, we are accessing the first element of the array using the syntax 0[arr]. This is an uncommon way to access array elements, but it works because of how arrays are implemented in C/C++.
Understanding the Syntax
Normally in C and C++, the expression arr[index] will be converted to *(arr + index). Now, when you write index[arr], this will be converted as *(index + arr), just the reverse the normal syntax. Thus, both arr[index] and index[arr] refer to the same memory location and give same value as output.
// Normal syntax arr[index]; // This is equivalent to *(arr + index) // Uncommon syntax index[arr]; // This is equivalent to *(index + arr)
This is a valid syntax, that is not known to many programmers. Using this types of syntax indicate the awareness of system level knowledge of arrays and pointer arithmetic of C/C++.