Ok, so I have the following function:
int functionX()
{
return strcmp(array1,array2)==0;
}
Why would anyone do this? the ==0 would suggest that this function will always return FALSE. Is this true or am I missing some exotic C syntax primers?
Ok, so I have the following function:
int functionX()
{
return strcmp(array1,array2)==0;
}
Why would anyone do this? the ==0 would suggest that this function will always return FALSE. Is this true or am I missing some exotic C syntax primers?
(strcmp(array1, array2) == 0)
is an expression that evaluates strcmp()
, which can return a negative, positive, or zero number. When two strings are the same, strcmp()
returns 0
.
== 0
is comparing the return value of strcmp()
with 0
. You would use this in the instance where you need functionX()
to return a "true" (non-zero) value when the two strings are the same. Specifically, strcmp(array1,array2)==0
will return 1
in that case, or 0
otherwise.
For more information on strcmp()
, take a look at its man page.
strcmp()
returns 0 iff its two arguments compare equal. In your example, functionX()
returns "true" iff array1
and array2
compare equal.
strcmp()
returns an integer, which is 0 if two strings are equivalent, non zero otherwise.
This function just "inverts" the result, in the sense that it will return 1 if the result is 0 or 0 if the result is non zero. In C, anything that is not 0 is considered "true" since there is no real boolean type (except with C99).
There's nothing exotic here... you are returning the result of the expression strcmp(array1, array2)==0
, which compares the result of strcmp
with 0 and returns 1 if they compare equal, 0 if they are different.
All in all, functionX
will return 1 if the result of the strcmp
is 0 (i.e. if the two compared strings are equal), 0 otherwise.
This construct compares the result of strcmp
with 0 and returns the result of the compare
Comparing with zero is the same than negating a boolean expression as in C you use integers as boolean values. So
return strcmp(array1,array2)==0;
is the same than
return !strcmp(array1,array2) ;
As strcmp only returns zero if both strings are equal then the expression will return true if strings are equal.