Check If Index Exists in an Array in C++

This tutorial will discuss about a unique way to check if index exists in an array in C++.

While using an array in C++, many times we need to access an element from array based on the index position.

But if we try to access an element at an index position that is invalid or that does not exist in the array, then it can result in undefined behaviour.

Therefore it is must to check if a given index position exists in the array or not before accessing element at that index position.

To check if index position is valid or not, first we need to fetch the size of the array, and then we can check, if the given index position is either greater than or equal to zero and less than the size of the array. If both condition satisfies then it means the index is valid

Let’s see the complete example,

#include <iostream>

int main()
{
    int arr[] = {4, 6, 2, 4, 8, 3, 3, 9, 10};

    int index = 3;

    // Get the size of array
    size_t len = sizeof(arr)/sizeof(arr[0]);

    // Check if index is less than the size
    // and greater than or equal to 0
    if(index >= 0 && index < len)
    {
        std::cout << "Yes, index is valid, and exists in Array. \n";
    }
    else
    {
        std::cout << "No, index is not valid, and does not exists in Array. \n";
    }
    return 0;
}

Output :

Yes, index is valid, and exists in Array.

Summary

Today we learned about a way to check if index exists in an array in C++. Thanks.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top