C strcmp

  • strcmp() is used to compare two strings to find whether they are same or different.

  • The two strings compared character by character until there is an end of one of the strings is reached.
  • If the two strings are identical, strcmp( ) returns a value zero.
  • If they’re not, it returns the numeric difference between the ASCII values of the first non-matching pairs of characters.
  • This function compares character by character.
  • Here the comparison is done by using ASCII values. So ‘A’ and ‘a’ is treated as different character.

Syntax for strcmp():


Below output is from GCC 7.2.0

For Visual C compiler output will be

Note: Output can vary depending on the compiler

– In the first strcmp(), the two strings are identical (Jerry == Jerry), therefore it returns 0.
– The second call to strcmp(), the first character of str1 doesn’t match with the str2, therefore it returns difference between ASCII value of ‘J'(74) and ASCII value of ‘F'(70) i.e, 74 – 70 =4.
– In the third call to the function, the first string Jerry doesn’t match with the second string Jerry boy, because ‘\0’ at end of the first string does not match with blank space. So it returns difference between the value of null character and ASCII value of ‘ ‘ blank space(32). 0-32= -32.
– In the fourth call to strcmp(), ‘J’ and ‘j’ treated as a different character. Therefore the result is the difference between ASCII value of ‘J'(74) and ASCII value of ‘j'(106) that is -32.

C strncmp():

This strncmp() function is used to compare some portion of one string with another string.

Syntax for strcmp()


This output 17 is because ‘a’ from string2 does not match with ‘r’. Therefore it returns difference between ASCII value of ‘r’ minus ASCII value of ‘a’.

C strcmpi()

This function is used to compare one string with another string. But this function negotiates the case. “A” and “a” are treated as same.

Syntax for strcmpi()


Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.