What does strcmp() exactly return in C?

Akhil Raj picture Akhil Raj · Jan 16, 2016 · Viewed 51.3k times · Source

I wrote this code in C:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

int main()
{
    char string1[20];
    char string2[20];
    strcpy(string1, "Heloooo");
    strcpy(string2, "Helloo");
    printf("%d", strcmp(string1, string2));
    return(0);
}

Should console print value 1 or difference between ASCII values of o and \0 character i.e. 111? On this website, it is written that this should give out put 111, but when I run it on my laptop, it shows 1. Why?

Answer

bolov picture bolov · Jan 16, 2016

From the cppreference.com documentation

int strcmp( const char *lhs, const char *rhs );

Return value

  • Negative value if lhs appears before rhs in lexicographical order.

  • Zero if lhs and rhs compare equal.

  • Positive value if lhs appears after rhs in lexicographical order.

As you can see it just says negative, zero or positive. You can't count on anything else.

The site you linked isn't incorrect. It tells you that the return value is < 0, == 0 or > 0 and it gives an example and shows it's output. It doesn't tell the output should be 111.