Having trouble with return values of strcmp(). How exactly does strcmp() work?

98 views Asked by At

I'm having an issue with solving a coding exercise and during debugging I've noticed that my strcmp() function doesn't work as I expected. The strcmp() function returns the wrong value compared to what I would expect. Perhaps I'm lacking some crucial undertanding of how strcmp() really works.

My code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
     char string[] = "dogs";
     char compare[] = "bark";

     int result = strcmp(string, compare);

     printf("int result = %d\n", result);
}

The return value of the program is: int result = 2 which is unexpected for me since the documentation of strcmp() states that:

strcmp(string_A, string_B)

  • string_A > string_B ==> return value >0

  • string_A < string_B ==> return value <0

  • string_A == string_B ==> return value =0

In my example strcmp(string, compare) or strcmp("dogs", "bark") the return value should be less than 0 since "dogs" < "bark" but it keeps returning 2 which I'm also not sure if it's expected behaviour that it always prints out the same integer.

2

There are 2 answers

1
dbush On BEST ANSWER

the return value should be less than 0 since "dogs" < "bark"

False.

Since 'd' comes after 'b', or more specifically since the character code for 'd' is greater than the character code for 'b', the former is considered greater, and therefore a value greater than 0 is returned.

1
Lundin On

Forget about alphabets and social constructs/conventions. Programmers/computers think differently than common folk. In general we just enumerate things from 0 and upwards.

Or in case of letters, computers use a symbol table code:

  • 'b' == 98
  • 'd' == 100
  • 98 < 100

For the same reason "Dog" is less than "dog", because 'D' == 68.