Array Subscript Operator in C++

Hey guys,
Today we will be learning what an Array Subscript operator is and how it works in C++.
So read on…

Array Subscript Operator in C++

What is an Array?

Array is nothing but a linear data structure that stores homogenous data in a contiguous form.
It is capable of random access and the elements are stored a fixed apart from each other.

It is static in nature meaning the size of the array has to be defined at compile-time and not run time.
Each element in an Array is given a particular index and is called using that index.

Syntax:

<datatype> <variable>[size];    //for declaring an array
<variable>[index] = <value>;    //for storing a value at a particular index.

Example:

int a[5];
a[2] = 30;

Hence 30 gets stored in the 2nd index position of the array.

What is an Array Subscript Operator?

As we saw in the example,
We store/read a value from a particular index in the array by using the <variable>[index] syntax.
But there is also another way of accessing it and that is by using <index>[variable] hence making this a postfix equation

So assume we have an array of type int and we call it using the variable ‘a’.
We can access an index, say 2, by using a[2].
We can also access its index by using 2[a].
Hence the square brackets [ ] are the subscript operators.

Explanation:
In an array the base address i.e. the first address and the index is what is most important.
If we want to access the second position, we use:

Address = Base Address + (index*DataSize)

So if we are accessing the second index of an integer type array, we are doing:

Address = Base Address + 2*4

Now when we define an array, the variable holds the base address and the index holds the displacement from the base address.

Also, read: How to Count number of elements in array in C++

 

Assume array a’s base address is 2000.
a[2] = 2000 + 2*4 = 2008
And
2[a] = 2*4 = 2000 = 2008

Because
a[b] = *((a)+(b)) = b[a]

Code Sample:

Take a look at the following code sample:

#include <iostream>
using namespace std;
int main()
{
    int a[5] = {10,20,30,40,50};
    cout<< a[2]<<endl;
    cout<< 2[a];
}

We have created an array of size 5 and defined the values 10 to 50 in each memory location.

We are then printing a[2] which is the 2nd index position which refers to 30.

And 2[a] which is also referring to the second index position which comes out to be 30.

Hence the output:

30
30

And that brings us to the end of this tutorial.
I hope you have understood how the Array Subscript Operator works and were able to execute it by yourself.
If you have any more doubts feel free to ask it in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *