OneBite.Dev - Coding blog in a bite size

Check If Array Is Empty In C++

Code snippet for how to Check If Array Is Empty In C++ with sample and detail explanation

In the realm of programming, particularly in C++, it is often essential to check whether an array is empty or not. This article will provide an easy step-by-step guide on how to perform this task.

Code Snippet: Checking Array Emptiness

To check if an array is empty, you can do the following:

#include<iostream>
using namespace std;

int main (){ 
    int arr[10] = {}; 
    if(sizeof(arr) == 0){
        cout<<"Array is empty"; 
    } else {
        cout<<"Array is not empty"; 
    }
}

Code Explanation for Checking Array Emptiness

The code snippet begins with the necessary standard includes and using statements. The statement, #include<iostream> is a directive for the compiler to include the iostream standard file that provides basic input and output services for C++. using namespace std; allows for the use of names in the std namespace without needing to prepend std:: to them.

Next, we have the main function, which is the initial point of our program. Inside this function, we declare an integer array named ‘arr’ with a size of 10.

int arr[10] = {}; 

This integer array ‘arr’ is initialized with all elements as zero (the common initial value).

The sizeof() function is then used to check if the array is empty:

if(sizeof(arr) == 0){

The sizeof() function in C++ returns the size, in bytes, of the object or type. In this case, sizeof(arr) will return the full size of the array. If your array is empty, sizeof(arr) will be equal to zero. Thus, if sizeof(arr) == 0 is true, it means your array is empty.

If the array is found to be empty, the statement cout<<"Array is empty"; will get executed, which prints “Array is empty” in the console. If it is not empty, cout<<"Array is not empty"; will be executed, printing “Array is not empty” instead.

Therefore, this simple block of code is a straightforward way to check if an array in C++ is empty. The primary advantage is its scalability - it can be easily used for arrays of any size, making it versatile in various situations.

c-plus-plus