Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

string - What does strcmp() exactly return in C?

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...