Home >Backend Development >C++ >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."; }
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)
is equivalent to:
if (&iar1[0] == &iar2[0])
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:
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."; }
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."; }
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!