Home > Backend Development > C++ > body text

Why does the `==` operator not work for comparing C arrays?

Mary-Kate Olsen
Release: 2024-11-16 17:00:03
Original
834 people have browsed it

Why does the `==` operator not work for comparing C   arrays?

Understanding Array Equality Comparison in C

Arrays are a fundamental data structure in C , but their equality comparison using the == operator often leads to unexpected results. This article aims to clarify why this occurs and provide alternatives for performing element-wise array comparisons.

Problem:

Consider the following code snippet:

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.";
}
Copy after login

Why does the output from this code indicate that the arrays are not equal?

Answer:

The equality operator == does not perform element-wise comparison for arrays. Instead, it compares the addresses of the arrays, which are always different because they are stored in distinct memory locations.

To understand why, we need to consider the concept of "decay." In C , arrays decay to pointers to their first elements when they are used in an expression. Therefore, the statement:

if (iar1 == iar2)
Copy after login

is equivalent to:

if (&iar1[0] == &iar2[0])
Copy after login

Since &iar1[0] and &iar2[0] represent different memory locations, the comparison evaluates to false.

Alternatives for Element-Wise Array Comparison:

Instead of comparing arrays with the == operator, there are two recommended approaches:

  1. Using a Loop:

To perform element-wise comparison, you can iterate over the arrays and check each element individually:

bool areEqual = true;
for (int i = 0; i < 5; ++i) {
    if (iar1[i] != iar2[i]) {
        areEqual = false;
        break;
    }
}

if (areEqual) {
    cout << "Arrays are equal.";
} else {
    cout << "Arrays are not equal.";
}
Copy after login
  1. Using std::array:

The C Standard Library provides the std::array type, which allows for element-wise comparison using the == operator:

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.";
}
Copy after login

The above is the detailed content of Why does the `==` operator not work for comparing C arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template