Values returned in comparison of strings in C

2

I was reading about header string.h functions in link and I came across with a strings function (very useful after all), such as strcmp(string1, string2) .

Depending on the first character that does not match, that is, it is different, string1 has a "value" greater or less than string2 . I was stuck with this, so I decided to test in this code:

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

int main (void)
{
     char teste[10];
     char teste2[10];

     printf("teste: ");
     scanf("%9[^\n]", teste);

     printf("teste2: ");
     scanf(" %9[^\n]", teste2);

     printf("%d", strcmp(teste, teste2));

     return 0;
}

When they are equal, a value of 0 is returned (as specified in link ). However, I could not understand why other values. The value returned is the difference of the characters according to the ASCII table? Otherwise, how does value assignment work?

    
asked by anonymous 03.08.2018 / 23:26

2 answers

4

According to documentation returns negative if the first argument comes before the second comparing lexicography ( alphabetical order) of the text, and you will receive a positive greater than zero if it comes after the second argument.

Each implementation is free to put the number you want there and can count the distance, how many characters it takes to make a difference, anything. The fact is you should not work on this detail, you usually just want to know if it's the same or different, and in some cases which one comes up against the other, but not about specific differences. So just check if it is less than 0, exactly 0, or if it is greater than 0.

    
03.08.2018 / 23:34
1

@Maniero has basically said all there was to say, but I'd like to take a look at the returns table in the documentation you've linked (translated by me):

____________________________________________________________________________________
| retorno | significado
| < 0     | O primeiro caratere que é diferente tem valor menor em str1 do que str2
| 0       | O conteudo de ambas as strings é igual                            
| > 0     | O primeiro caratere que é diferente tem valor maior em str1 do que str2
___________________________________________________________________________________

Where str1 and str2 are the two parameters of the function:

int strcmp ( const char * str1, const char * str2 );

Note that this is all that is written in relation to the return. So any other interpretation you make is already interpreting more things, which are potentially implementation details.

    
03.08.2018 / 23:58