saving . . . saved String function strcmp results has been deleted. String function strcmp results has been hidden .
String function strcmp results
As explained by Ashiwini, Why did the strcmp results come as 1, 0? Will it be different for each case? Is it like true or false? Can you please elaborate on how the strcmp function works?

C-and-Cpp String-Library-Functions 05-06 min 50-60 sec 08-07-21, 10:40 p.m.


Dear ruthwikn20,

The function 'strcmp' compares the two string arguments. It compares both the strings character by character until the NULL character. If all the characters in both the strings are same including the NULL character, it is declared as matched, and hence 0 is reported. If not, 1 is reported. In the POSIX standards, 0 means success and 1 means failure and this can be equated to TRUE of FALSE respectively.
Hope this answers your question.

-- Spoken Tutorial Team
15-07-21, 8:26 p.m. nags
I have tried various examples with the 'strcmp' function and have noticed results in numbers other than 0 and 1 which has confused me.
15-07-21, 8:33 p.m.
int main()
    char str1[] = "Ice";
    char str2[] = "Cream";
    int i,j;
    i = strcmp(str1,"Jello");
    j = strcmp(str2,"Cream");
    printf("%d, %d\n", i, j);
    return 0;
15-07-21, 8:35 p.m.
-1 , 0
15-07-21, 8:35 p.m.

Login to add comment

Dear ruthwikn20,
     Thanks for pointing out. I did not mention non-zero in my previous post. 1 or -1 should be read as non-zero. That means, if the match is successful, it will definitely return 0 (zero), and if the match is unsuccessful it will return something non-zero . Now, the non-zero comes from the comparison of ASCII values. In the program that you supplied above, ASCII value of 'I' for the string 'Ice' is 73, and ASCII value of 'J' for the string 'Jello' is 74. The function 'strcmp' will calculate the difference in ASCII values of 'I' and 'J', i.e. 73-74 = -1.  Hence, you get -1. Try out different options and see for yourself. Hope to answer your question. 

--Spoken Tutorial Team.
16-07-21, 1:14 p.m. nags
Now I get it. It basically strcmp calculates the difference in ASCII value and continues it till it reaches a non-zero value. Thank you for the explanation.
16-07-21, 10:18 p.m.

Login to add comment

Log-in to answer to this question.