0

I can't seem to understand why strcmp doesnt return 65 in the case of strcmp("A", ""), but returns 1 instead.

while strcmp("A", "B") does a substitution returning -1.

RimaL878
  • 23
  • 3
  • 6
    The spec for strcmp doesn't state that it must return the difference between the ASCII values of the two mismatching characters; it simply states that it must return a positive, zero or negative number. – Robert Harvey Mar 26 '21 at 16:02
  • 2
    Read the documentation of `strcmp` closely, especially the part dealing with the return value. Also try `strcmp("A", "C")` – Jabberwocky Mar 26 '21 at 16:03
  • 1
    ..and do the same for every standard function before making assumptions on their works and asking why they don't behave per your assumptions. – Eugene Sh. Mar 26 '21 at 16:05
  • Thank you! I thought that you'd have to explicitly make the return value boolean with `!!strcmp(..)`. – RimaL878 Mar 26 '21 at 16:06
  • 2
    `!!` doesn't make a value of type `bool`... it makes a `int` with value `0` or `1`. For a value of type `bool` you need a cast: `(bool)strcmp(...)`; but the `int` is good enough in 99.9999% of situations. – pmg Mar 26 '21 at 16:07
  • @pmg is there any operator that return `bool`? Except `(bool)`. I think there isn't.. – Eugene Sh. Mar 26 '21 at 16:08
  • [https://www.gnu.org/software/libc/manual/html_node/String_002fArray-Comparison.html](https://www.gnu.org/software/libc/manual/html_node/String_002fArray-Comparison.html) states that "The strcmp function compares the string s1 against s2, returning a value that has the same sign as the difference between the first differing pair of bytes (interpreted as unsigned char objects, then promoted to int).", so I didnt make an assumption. – RimaL878 Mar 26 '21 at 16:09
  • 2
    @RimaL878 Yes, you did. What you quoted does not imply that you necessarily should get the result 65. It only says you should get a positive number. The rest is your assumption. :) – klutt Mar 26 '21 at 16:11
  • The key part of that quote is "same sign", that's all the standard guarantees. – Blastfurnace Mar 26 '21 at 16:12
  • I don't recall any operator that works on and returns a `_Bool`... even if there was the `_Bool` would very very fast be converted to something else (`int` in all likelyhood) – pmg Mar 26 '21 at 16:13
  • yeah, thank you all, I was just trying to rewrite it using asm and was confused. – RimaL878 Mar 26 '21 at 16:14

0 Answers0