Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does strcmp() exactly return in C?

Tags:

c

string

strcmp

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?

like image 844
Akhil Raj Avatar asked Jan 16 '16 08:01

Akhil Raj


1 Answers

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.

like image 136
bolov Avatar answered Sep 22 '22 23:09

bolov