C strcmp() Function

The strcmp() function in C is used to compare two strings. It compares each character of the strings and returns a value based on the result of the comparison. The function is defined in the string.h library.

Syntax of strcmp()

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

Syntax:

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

The function takes two arguments:

The function returns:

Example of strcmp() Function

Here is an example that demonstrates how the strcmp() function works:

Example:

                        
#include <stdio.h>
#include <string.h>
int main() 
{
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[] = "Hello";
    
    int result1 = strcmp(str1, str2);  // Comparing "Hello" with "World"
    int result2 = strcmp(str1, str3);  // Comparing "Hello" with "Hello"
    
    // Output the results of comparisons
    printf("Comparison Result 1: %d\n", result1);  // Output will be negative
    printf("Comparison Result 2: %d\n", result2);  // Output will be 0
                   
    return 0;
}
                        
                    

Output:

Comparison Result 1: -1
Comparison Result 2: 0

Explanation of the Example

In this example:

Important Notes