C Programming - Library Functions - Discussion
Discussion Forum : Library Functions - True / False Questions (Q.No. 5)
5.
If the two strings are found to be unequal then strcmp returns difference between the first non-matching pair of characters.
Answer: Option
Explanation:
g = strcmp(s1, s2); returns 0 when the strings are equal, a negative integer when s1 is less than s2, or a positive integer if s1 is greater than s2, that strcmp() not only returns -1, 0 and +1, but also other negative or positive values(returns difference between the first non-matching pair of characters between s1 and s2).
A possible implementation for strcmp() in "The Standard C Library".
int strcmp (const char * s1, const char * s2)
{
for(; *s1 == *s2; ++s1, ++s2)
{
if(*s1 == 0)
return 0;
}
return *(unsigned char *)s1 < *(unsigned char *)s2 ? -1 : 1;
}
Discussion:
4 comments Page 1 of 1.
Christobal said:
10 years ago
The code example shown won't return values other than 0, 1 and -1. This is not a complete solution if the function is supposed to return the difference between the first non-matching characters.
Vishal said:
1 decade ago
How and When will it return values other than 0, -1 or 1?
Sin said:
1 decade ago
This is the compiler implementation of strcmp function.
for loop checks first two characters in string if equal continues to next characters and checks if null if null prints 0 else skips the for lop then decides which character is greater neglect this in the last line. Its just type of pointer (unsigned char *)
if first char lesser then -1 else 1. If condition true then 1 else 2 ((condition?1:2)).
for loop checks first two characters in string if equal continues to next characters and checks if null if null prints 0 else skips the for lop then decides which character is greater neglect this in the last line. Its just type of pointer (unsigned char *)
if first char lesser then -1 else 1. If condition true then 1 else 2 ((condition?1:2)).
Kumar said:
1 decade ago
Can you explain the last statement?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers