user1438832 user1438832 - 18 days ago 9
C++ Question

Is my implementation of string comparison is right?

#include <iostream>
using namespace std;

bool isEqual(const char *a,const char *b)
{
int lengthA=strlen(a);
int lengthB=strlen(b);
if( lengthA != lengthB)
{
return false;
}
int intLength=sizeof(int);
int *ptrA;
int *ptrB;
int i=0;
for(;i<lengthA/intLength;i++)
{
ptrA=(int*)(a+(i*intLength));
ptrB=(int*)(b+(i*intLength));
if(( (*ptrA) ^ (*ptrB) ))
{
return false;
}
}
i=lengthA-lengthA%intLength+1;
for(;i<lengthA;i++)
{
if(a[i] != b[i])
{
return false;
}
}
return true;
}

int main()
{
cout<<isEqual("asasa","asasa")<<endl;
return 0;
}


My idea is not to compare char by char but insted typecast it to int(4 byte comparison) and do the xor operation to test whether they are equal or not.
My question is that if only comparison require(true,false) is it right.

Answer

It is undefined behaviour. (You are dereferencing an pointer to int where the pointed-to object is not int.)

The code will almost certainly be slower than strcmp (which typically does something like this iff the pointers are suitably aligned - possibly with the loop unrolled a few times).