strcmp() Function

The strcmp() function in C is used to compare two strings by evaluating each character sequentially until a difference is encountered or the end of the strings is reached. It performs a binary comparison and returns an integral value that reflects the lexicographical relationship between the two strings.


Syntax of strcmp()

</>
Copy
int strcmp(const char *str1, const char *str2);

Parameters

ParameterDescription
str1C string to be compared.
str2C string to be compared.

The function compares the strings character by character, stopping when a difference is found or when a null-character is encountered. It performs a binary comparison, meaning that the numerical values of the characters are used. For locale-specific comparisons, consider using strcoll().


Examples for strcmp()

Example 1: Comparing Identical Strings

This example demonstrates how strcmp() returns 0 when comparing two identical strings.

Program

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

int main() {
    const char *s1 = "Hello";
    const char *s2 = "Hello";
    int result = strcmp(s1, s2);
    printf("Result: %d\n", result);
    return 0;
}

Explanation:

  1. Two identical strings are defined.
  2. The strcmp() function compares them character by character.
  3. Since both strings are identical, the function returns 0.
  4. The output confirms that the strings are equal.

Output:

Result: 0

Example 2: Comparing Different Strings (Negative Result)

This example shows how strcmp() returns a negative value when the first non-matching character in the first string has a lower value than in the second string.

Program

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

int main() {
    const char *s1 = "abc";
    const char *s2 = "abd";
    int result = strcmp(s1, s2);
    printf("Result: %d\n", result);
    return 0;
}

Explanation:

  1. The first string is “abc” and the second is “abd”.
  2. The comparison proceeds until the third character where ‘c’ is less than ‘d’.
  3. The function returns a negative value to indicate that the first string is lexicographically smaller.
  4. The result is printed accordingly.

Output:

Result: -1

Example 3: Comparing Different Strings (Positive Result)

This example demonstrates how strcmp() returns a positive value when the first string is lexicographically greater than the second string.

Program

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

int main() {
    const char *s1 = "world";
    const char *s2 = "hello";
    int result = strcmp(s1, s2);
    printf("Result: %d\n", result);
    return 0;
}

Explanation:

  1. The first string is “world” and the second string is “hello”.
  2. The comparison finds that the first character of “world” (‘w’) is greater than that of “hello” (‘h’).
  3. The function returns a positive value to indicate that the first string is lexicographically greater.
  4. The output displays the resulting positive value.

Output:

Result: 15