Home > Backend Development > C++ > Why Do C Arrays Compare as Unequal Using the == Operator?

Why Do C Arrays Compare as Unequal Using the == Operator?

Mary-Kate Olsen
Release: 2024-12-03 00:12:11
Original
517 people have browsed it

Why Do C   Arrays Compare as Unequal Using the == Operator?

Understanding Array Equality Comparison in C

When comparing arrays using the == operator, programmers often encounter unexpected results. To delve into this issue, let's analyze the code snippet below:

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

Despite containing identical elements, the code outputs "Arrays are not equal." To understand this behavior, we must examine how C handles array comparisons.

When comparing arrays using ==, the expression reduces to comparing the pointers to the first elements of each array. However, in this case, iar1 and iar2 represent two distinct arrays stored at different memory addresses. Thus, they evaluate to unequal pointers, resulting in the "not equal" output.

To perform an element-wise comparison, alternative approaches can be employed. One method involves using a loop to compare each element individually. Alternatively, for C 11 and later, std::array provides a more structured approach for array handling. In the revised code below, std::array is utilized to represent the arrays, and the == operator performs element-wise comparison, yielding the expected result:

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

}
Copy after login

The above is the detailed content of Why Do C Arrays Compare as Unequal Using the == Operator?. 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