Home  >  Article  >  Backend Development  >  Why Does `==` Not Work for Array Equality Comparison in C ?

Why Does `==` Not Work for Array Equality Comparison in C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-16 11:26:03395browse

Why Does `==` Not Work for Array Equality Comparison in C  ?

Why does array equality comparison using == not work?

In C , the equality operator (==) compares the memory addresses of arrays, rather than their contents. This behavior can lead to confusion, as it differs from the intuitive expectation of comparing array elements element-wise.

Consider the following code:

int main()
{
    int iar1[] = {1, 2, 3, 4, 5};
    int iar2[] = {1, 2, 3, 4, 5};

    if (iar1 == iar2)
        cout << "Arrays are equal.";
    else
        cout << "Arrays are not equal.";
}

In this code, two arrays are created with identical contents. However, the output states that the arrays are not equal. This is because the == operator compares the memory addresses of the arrays, which are different for each array.

To perform element-wise comparison of arrays, one can either use a loop or utilize the std::array class. The std::array class provides a slightly different interface for working with arrays and supports direct equality comparison.

Example using a loop:

bool arraysEqual(int *arr1, int *arr2, int size)
{
    for (int i = 0; i < size; ++i)
    {
        if (arr1[i] != arr2[i])
            return false;
    }
    return true;
}

Example using std::array:

#include <array>

int main()
{
    std::array<int, 5> iar1 = {1, 2, 3, 4, 5};
    std::array<int, 5> iar2 = {1, 2, 3, 4, 5};

    if (iar1 == iar2)
        cout << "Arrays are equal.";
    else
        cout << "Arrays are not equal.";
}

The above is the detailed content of Why Does `==` Not Work for Array Equality Comparison in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn