
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Why is a[i] == i[a] in C/C++ arrays?
Here we will see one amazing trick in C or C++. The array subscript A[i] can also be written as i[a]. In C/C++ E1[E2] is defined as (*((E1) + (E2))). The compiler performs arithmetic internally to access the array elements. Because of the conversion of rules, that is applied to the binary + operator, if E1 is an array object, and E2 is an integer, then E1[[E2] signifies the E2th element in the E1 array. So A[B] can be defined as *(A + B), so B[A] = *(B + A). so they are basically the same thing.
Example
#include <iostream> using namespace std; int main() { int array[] = {1, 2, 3, 4, 5, 6, 7}; cout << "array[5] is " << array[5] << endl; cout << "5[array] is " << 5[array]; }
Output
array[5] is 6 5[array] is 6
- Related Questions & Answers
- Is there a performance difference between i++ and ++i in C++?
- How do I use arrays in C++?
- Is there a performance difference between i++ and ++i in C++ program?
- Minimize (max(A[i], B[j], C[k]) – min(A[i], B[j], C[k])) of three different sorted arrays in C++
- Maximizing the elements with a[i+1] > a[i] in C++
- Minimize (max(A[i], B[j], C[k]) – min(A[i], B[j], C[k])) of three different sorted arrays in Python
- What is the difference between ++i and i++ in c?
- What is the difference between ++i and i++ in C++?
- Find d to maximize the number of zeros in array c[] created as c[i] = d*a[i] + b[i] in C++
- How do I identify if a string is a number in C#?
- When can I use a forward declaration C/C++?
- When can I use a forward declaration in C/C++?
- How do I catch a Ctrl+C event in C++?
- When to use i++ or ++i in C++?
- Count pairs (i,j) such that (i+j) is divisible by both A and B in C++
Advertisements