0

Some C code I am working on has the following line,

strcmp(str1+4, str2);

strcmp returns,

  • 0 for equal ASCII values of both strings

  • '1' for where str1 has a greater ASCII value than str2

  • '-1' where str1 has a lesser ASCII value than str2

Given this notation, is it possible 'str1+4' is the ASCII value of 'str1' and then adding 4 or is it indicative of something else?

I looked around online and through documentation without much in the way of luck and figured I'd ask here to clarify my understanding.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • 1
    This question really has nothing to do with `strcmp`, which simply takes a pointer to a string. The thing you should be asking is what does `str1+4` mean, when `str1` is a `char *`. Search for "pointer arithmetic". – David Grayson Nov 26 '22 at 04:41
  • That line compares str1 (from the 5th character) and the whole str2. `char * foo = "stackOverflow";` foo+3 = "ckOverflow", it's the same as &foo[3] by definition – AR7CORE Nov 26 '22 at 04:57
  • 2
    Your statement about return value of `strcmp` is wrong. It can return any number, not only `-1`, `0`, `1`. You need to read the spec carefully. – Gerhardh Nov 26 '22 at 05:11
  • concreteCozy, "'1' for where str1 has a greater ASCII value than str2" is amiss too. ASCII only well defined for 0-127. `strcmp()` return a positive value when the compared strings differ, as `unsigned char` values (0-255) and first first is greater than the 2nd. – chux - Reinstate Monica Nov 26 '22 at 05:18

0 Answers0