Strcmp() Function in C

The strcmp() function is a commonly used function in the C programming language. It is used to compare two strings and determine their relative ordering. The function takes two string arguments and returns an integer value based on the comparison result.

Syntax

The syntax of the strcmp() function is as follows:

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

Parameters

The strcmp() function takes two parameters:

  • str1: A pointer to the first string to be compared.
  • str2: A pointer to the second string to be compared.

Return Value

The strcmp() function returns an integer value based on the comparison result:

  • If the two strings are equal, it returns 0.
  • If the first string is greater than the second string, it returns a positive value.
  • If the first string is less than the second string, it returns a negative value.

Example Usage

Here is an example that demonstrates the usage of the strcmp() function:

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

int main() {
    char str1[] = "apple";
    char str2[] = "banana";

    int result = strcmp(str1, str2);

    if (result == 0) {
        printf("The strings are equaln");
    } else if (result < 0) {
        printf("The first string is less than the second stringn");
    } else {
        printf("The first string is greater than the second stringn");
    }

    return 0;
}

In this example, the strcmp() function is used to compare the strings “apple” and “banana”. The result is then checked to determine the relative ordering of the strings.

Important Considerations

When using the strcmp() function, it is important to keep the following considerations in mind:

  • The strcmp() function compares the strings character by character, starting from the first character. It stops as soon as it finds a difference or reaches the end of either string.
  • The comparison is case-sensitive, so uppercase and lowercase letters are considered different.
  • The function relies on the ASCII values of the characters to determine their ordering. Therefore, the result may not be intuitive for strings with non-ASCII characters.

The strcmp() function is a powerful tool in the C programming language for comparing strings. By understanding its syntax, parameters, return value, and important considerations, you can effectively use this function to determine the relative ordering of strings in your programs.

Scroll to Top