As mentioned by other answers:
if (iar1 == iar2)
This performs comparison between pointers, because ==
forces array-to-pointer conversion. C++ folks often refer to this as decay.
The condition is true
only if iar1
and iar2
are literally the same array.
Solution A - Use std::array
(C++11)
std::array<int> iar1 = {1, 2, 3, 4, 5};
std::array<int> iar2 = {1, 2, 3, 4, 5};
if (iar1 == iar2) // true
std::array
avoids a lot of C-style array problems in general, so you might want to replace all your uses of int[]
with it.
Solution B - Use std::span
s(C++20)
if (std::span{iar1} == std::span{iar2})
std::span
is a lightweight non-owning view into our array.
Wrapping a range in a std::span
and using the ==
operator should be just as cheap as using standard library algorithms.
Solution C - Use std::equal
(C++98) or std::ranges::equal
(C++20)
if (std::ranges::equal(iar1, iar2))
// the last argument is optional, but may be helpful for optimizations
if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2), std::end(iar2))
C++26 will likely remove array comparison
On a language evolution note, C++23 has deprecated array comparisons, and based on consensus in P2865 - Remove Deprecated Array Comparisons from C++26, it will likely be removed from the language.
In the future, your code could simply produce an error, and this pitfall will no longer exist.