For two strings s1 and s2 in C, what does strcmp(s1, s2) return if the strings are identical in content and length?
-
A-1
-
B1
-
C0
-
DYes
-
ENone of the above
Answer
Correct Answer: 0
Explanation
Introduction / Context:strcmp is the canonical C function for lexicographic comparison of two null-terminated strings. Interpreting its return value correctly is crucial for sorting, searching, and equality checks.
Given Data / Assumptions:
- s1 and s2 are valid null-terminated strings.
- We use the standard strcmp contract.
- No locale-specific collation overrides are considered.
Concept / Approach:strcmp returns an integer less than 0 if s1 < s2, greater than 0 if s1 > s2, and exactly 0 if s1 and s2 are equal (same characters in the same order with the same length). Therefore, equality corresponds to a return value of 0, not a Boolean value like 'Yes'.
Step-by-Step Solution:Call strcmp(s1, s2).If return == 0, the strings are identical.If return < 0, s1 precedes s2; if > 0, s1 follows s2.Use equality to branch or to confirm matches before further processing.
Verification / Alternative check:strcmp("cat","cat") returns 0; strcmp("ant","bee") < 0; strcmp("dog","cat") > 0.
Why Other Options Are Wrong:
- -1 or 1 are specific negative/positive values; the standard only promises <0 or >0, not exact -1/1.
- Yes is not a valid return type for strcmp.
Common Pitfalls:Testing for return == 1 or == -1 specifically; instead, test < 0, == 0, or > 0.
Final Answer:0.