What does == test when applied to arrays in C++?
Does it test for type equivalence or equal memory locations?

Recommended Answers

All 3 Replies

I'd have to say the contents. To check if they refer to same memory locations, you will have to dereference when you compare.

Let's say you have arrays: int arr1[N], arr2[N]; Then arr1 and arr2 are actually pointers to first locations in arrays, so this would be true:

arr1== &arr1[0]
&&
arr2==&arr2[0]

Now you can see where I'm going at:

arr1 == arr2
//is like
&arr1[0] == &arr2[0]

So it evaluates adresses of these two arrays, and if they are same it is true.

If you want to really evaluate arrays, you will have to write function that evaluates each member of array

Think of arrays as pointers to the start of a stream of data. When comparing them, you are comparing the memory address of the first value of the array with the second. These will never be the same, unless one array references another. Basically it's a redundant test that shouldn't be done. To compare arrays, you would need to overload the == operator like so...

bool operator==(array array1, array array2)
{
    if (array1.iSize != array2.iSize)
         return false;   //if the sizes are different, bail
    for(int i(0); i < array1.iSize; ++i)
        if (array1[i] != array2[i])
           return false;
    return true;
}

Where array1 and array2 are user defined data types containing a size member and overloaded [] operator.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.