Values returned in comparison of strings in C

Asked

Viewed 181 times

2

I was reading about some of the functions of header string.h in http://www.cplusplus.com/reference/cstring/ and I came across some comparison functions between strings (useful after all), such as, for example, strcmp(string1, string2).

Depending on the first character that does not match, that is, it is different, string1 has a "value" higher or lower than the string2. I was blinded by this, so I decided to test 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, the value 0 is returned (as specified in http://www.cplusplus.com/reference/cstring/strcmp/). However, I could not understand why of other values. Is the returned value the difference of the characters according to the ASCII table? Otherwise, how the value assignment works?

2 answers

4


In accordance with the documentation returns negative if the first argument comes before the second by comparing the lexicography (alphabetical order) of the text, and 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 you can count the distance, how many characters it takes to make a difference, anything. The fact is that you should not work with this detail, usually you just want to know whether it is the same or different, and in some cases which one comes anates of 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.

1

The @Maniero already said basically everything there was to say, but I take the opportunity to put the table of returns that is in the documentation that you 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
___________________________________________________________________________________

In which 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 there in relation to the return. So any other interpretation you make is already interpreting too many things, which are potentially implementing details.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.