C Compare String: strcmp()

The strcmp() function in the C programming language is used to compare two strings. It compares the characters of two strings lexicographically and returns an integer value indicating the result of the comparison.

The syntax of strcmp() function is:

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

The str1 and str2 parameters are pointers to the null-terminated strings that you want to compare.

The return value of strcmp() is as follows:

  • If str1 is equal to str2, it returns 0.
  • If str1 is greater than str2, it returns a positive value.
  • If str1 is less than str2, it returns a negative value.

Here’s an example usage of strcmp():

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

int main() {
    char str1[] = "Hello";
    char str2[] = "World";

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("The strings are equal.\n");
    } else if (result < 0) {
        printf("str1 is less than str2.\n");
    } else {
        printf("str1 is greater than str2.\n");

    return 0;

In the example above, the strcmp() function is used to compare the strings “Hello” and “World”. The result is stored in the result variable, and then it is checked to determine the relationship between the strings. In this case, since “Hello” is less than “World” lexicographically, the output will be “str1 is less than str2”.