C strcmp()

The strcmp() function compares two strings and returns 0 if both strings are identical.

C strcmp() Prototype

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

The strcmp() function takes two strings and return an integer.

The strcmp() compares two strings character by character. If the first character of two strings are equal, next character of two strings are compared. This continues until the corresponding characters of two strings are different or a null character '\0' is reached.

It is defined in string.h header file.

Return Value from strcmp()

Return Value Remarks
0 if both strings are identical (equal)
negative if the ASCII value of first unmatched character is less than second.
positive integer if the ASCII value of first unmatched character is greater than second.

Example: C strcmp() function

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

int main()
    char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
    int result;

    // comparing strings str1 and str2
    result = strcmp(str1, str2);
    printf("strcmp(str1, str2) = %d\n", result);

    // comparing strings str1 and str3
    result = strcmp(str1, str3);
    printf("strcmp(str1, str3) = %d\n", result);

    return 0;


strcmp(str1, str2) = 32
strcmp(str1, str3) = 0

The first unmatched character between string str1 and str2 is third character. The ASCII value of 'c' is 99 and the ASCII value of 'C' is 67. Hence, when strings str1 and str2 are compared, the return value is 32.

When strings str1 and str3 are compared, the result is 0 because both strings are identical.