Check if two char arrays are equals in C++

This tutorial will discuss about a unique way to check if two char arrays are equals.

We can use the strcmp() function to compare two char arrays. It accepts two strings (char pointers) as arguments, and compares both the strings alphabetically. If both the strings are equal then it will return 0.

So, to check if two char arrays are equal or not, we need to pass both the char arrays into the strcmp() function. If it returns 0, then it means both the char arrays or strings are equal.

Let’s see the complete example,

#include <iostream>
#include <string.h>

int main()
{
    char firstArr[10] = "sample";
    char secondArr[10]= "sample";

    // Check if two char arrays are equal
    if(strcmp(firstArr, secondArr) == 0)
    {
        std::cout<<"Both Char Arrays are equal \n";
    }
    else
    {
        std::cout<<"Both Char Arrays are not equal \n";
    }
    return 0;
}

Output :

Both Char Arrays are equal

Summary

Today we learned about several ways to check if two char arrays are equals. 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