What are the return values of strcmp function in c?
Understanding the Return Values of strcmp Function
Introduction
The strcmp function is a fundamental string comparison function in the C programming language. It is used to compare two strings and determine their relative order in lexicographical terms. strcmp returns an integer value that indicates the result of the comparison.
Return Values
The return value of strcmp can be interpreted as follows:
-
Negative Value ( < 0 ):
- When the first string is lexicographically less than the second string.
- Example: strcmp("apple", "banana") returns a negative value.
-
Zero ( 0 ):
- When both strings are equal.
- Example: strcmp("hello", "hello") returns 0.
-
Positive Value ( > 0 ):
- When the first string is lexicographically greater than the second string.
- Example: strcmp("zebra", "apple") returns a positive value.
Usage Example
#include
#include
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if(result < 0)
printf("%s is less than %s\n", str1, str2);
else if(result == 0)
printf("%s is equal to %s\n", str1, str2);
else
printf("%s is greater than %s\n", str1, str2);
return 0;
}
Summary
Understanding the return values of strcmp is crucial for effective string comparison in C programming. By utilizing these return values, you can make informed decisions in your code based on the relative order of strings.
For further information and examples, plese visit C-Programming From Scratch to Advanced 2023-2024
Remember to replace the example code and links with actual content and relevant sources if necessary. This structure provides a clear explanation of the topic, a usage example, and additional resources for further learning. [www.electro4u.net]