1

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?

Evert
  • 563
  • 1
  • 5
  • 13
  • What is the problem? If the strcmp returns 0, it means the strings are equal. Otherwise, one is greater that the other, depending on the sign of the result (negative or positive result). – Rolice Dec 23 '11 at 15:23
  • You return the result of the evaluation "strcmp(array1,array2)==0". If strcmp(array1, array2) does indeed equal 0, then you'll return true, otherwise false. It's no more exotic than "return 1==1;", except that example will obviously always return true. – Andreas Eriksson Dec 23 '11 at 15:26

6 Answers6

1

(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.

Dan Fego
  • 13,644
  • 6
  • 48
  • 59
1

strcmp() returns 0 iff its two arguments compare equal. In your example, functionX() returns "true" iff array1 and array2 compare equal.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

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).

fge
  • 119,121
  • 33
  • 254
  • 329
1

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
0

This construct compares the result of strcmpwith 0 and returns the result of the compare

juergen d
  • 201,996
  • 37
  • 293
  • 362
0

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.

Gabriel
  • 3,319
  • 1
  • 16
  • 21