The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

strcmp() In C

Purpose of strcmp()

strcmp() is one of the inbuilt string function in c programming which is used to compare two strings, if the strings are same then the function returns 0. Otherwise it returns a nonzero value.

How strcmp() Works

The following diagram clearly illustrate the working principle of strcmp() inbuilt string function in C.

strcmp() in c

Syntax - strcmp()

  • strcmp() accepts two parameters.
  • Both parameters must be a string.
  • To use strcmp() inbuilt string function in C, we need to declare #include<string.h> header file.
Syntax
strcmp(str1, str2);

C Program - strcmp()

Let us work through strcmp() function. In the following program we will compare two strings using strcmp() inbuilt string function.

c-using-strcmp.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is strcmp", str2[20] = "this is strcmp";
if(strcmp(str1, str2) == 0)
printf("The strings str1 and str2 are same ");
return 0;
}
The strings str1 and str2 are same

Note:

The above program defines the function strcmp(), which is used to compare two strings. Here, str1 and str2 are same, so it returns 0 and prints the statement inside the condition.

C Program - Without strcmp()

Let us compare two strings without using inbuilt string function strcmp().

c-without-strcmp.c
#include <stdio.h>
#include<string.h>
int main()
{
char str1[20] = "this is strcmp";
char str2[20] = "this is strcmp";
int i, j = 0;
for(i=0; str1[i]!='\0'; i++){
if(str1[i] == str2[i]) {
j++;
}
else {
j++;
printf("The strings str1 and str2 are not equal");
break;
}
}
if(i==j)
printf("The strings str1 and str2 are equal");
return 0;
}
The strings str1 and str2 are same

Note:

The above program looks verbose but yields the same result.

strcmp() table

Type Return Value
str1 > str2. 1
str1 == str2. 0
str1 < str2. -1

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report