Home > Article > Backend Development > Why Does `==` Fail to Compare Arrays for Equality in C ?
Array Equality Comparison Mystery: Why Does == Not Equal Arrays?
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."; }
To the dismay of many, this code incorrectly prints "Arrays are not equal." Why does this comparison fail so unexpectedly?
Array Decaying Unraveled
The reason lies in the concept of "array decay." In C , arrays automatically decay to pointers to their first elements when used in certain contexts, like in the comparison operator here. As a result, iar1 and iar2 effectively compare the addresses of the first elements, which are distinct for different arrays.
Element-Wise Comparison
To correctly determine if two arrays have the same elements, an element-wise comparison is required. To achieve this, one can either implement a loop to compare each element individually or utilize the std::array container from the C Standard Library.
std::array to the Rescue
std::array is a fixed-size container that behaves as an array but provides additional functionality, including the ability to compare two arrays for element-wise equality. Here's a revised code snippet using std::array:
std::array<int, 5> iar1 {1, 2, 3, 4, 5}; std::array<int, 5> iar2 {1, 2, 3, 4, 5}; if (iar1 == iar2) { // arrays contents are the same } else { // not the same }
Now, the code will correctly output "Arrays are equal."
Recapping the Wisdom
The above is the detailed content of Why Does `==` Fail to Compare Arrays for Equality in C ?. For more information, please follow other related articles on the PHP Chinese website!