Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading