Zeyad Etman Zeyad Etman - 2 months ago 13
C++ Question

what's the difference between strcmp and the ordinary equal sign (==) in c++?

What's the difference between

and the ordinary equal sign (==) in c++?

In code language What's the difference between those two lines:

char str1,str2;
if(str1 == str2)


if(strcmp (str1,str2))


I suppose that str1 and str2 are either character arrays or pointers of type char *. If so then in this condition

if(str1 == str2)

character arrays (if the identifiers denote character arrays) are implicitly converted to pointers to their first elements and as result there is a comparison of two addresses that are stored in str1 and str2.

As for the standard function strcmp then it compares strings pointed to by the pointers.

That is in the first case the pointers themselves are compared while in the second case the strings pointed to by the pointers are compared.

For example if you have two declarations like this

char str1[] = "Apple";
char str2[] = "Apple";

it is evident that the two arrays occupy different extents of memory. So the comparison

str1 == str2 

yields always false. In this comparison the left and the right expressions are converted to pointers to the first elements of the arrays.

However if to apply the standard C function strcmp like this

strcmp( str1, str2 )

then it returns 0 saying that the two arrays store equal strings.