This function compares two strings lexicographically.
Syntax:
int strcmp(const char *str1, const char *str2);
Parameters:
- str1: A pointer to the first string.
- str2: A pointer to the second string.
Return Value:
- if str1 is lexicographically less than str2 then value will be less than 0.
- if str1 is equal to str2 then value will be 0.
- if str1 is lexicographically greater than str2 then value will be greater than 0.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "My";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("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;
}
Output:
str1 is less than str2.
C strcmp() method – Interview Questions
Q 1: What is the use of strcmp()?
Ans: To compare two strings lexicographically.
Q 2: What values can strcmp() return?
Ans: 0, positive, or negative value.
Q 3: When does strcmp() return 0?
Ans: When both strings are equal.
Q 4: Is strcmp() case-sensitive?
Ans: Yes, it is case-sensitive.
Q 5: Which header file contains strcmp()?
Ans: .
C strcmp() method – Objective Questions (MCQs)
Q1. What does the strcmp() function in C do?
Q2. What will be the output of the following code?
What will be the output of the following code?
Q3. Which header file is required to use the strcmp() function?
Q4. What is the return value of strcmp("Code", "Code")?
Q5. What does a positive return value from strcmp() indicate?