In C, consider strcmp on two user-entered strings using gets (unsafe). What output should you expect from this program and why can it vary? #include<stdio.h> #include<string.h> int main() { char str1[5], str2[5]; int i; gets(str1); gets(str2); i = strcmp(str1, str2); printf("%d ", i); return 0; } Choose the most accurate description of the printed value.

Difficulty: Medium

Correct Answer: Unpredictable integer value

Explanation:


Introduction / Context:
This question probes how strcmp reports lexical ordering and why its numeric return value is implementation-dependent. It also highlights the dangers of gets, which can overflow buffers and is removed from modern C. The essential learning: strcmp returns a negative, zero, or positive integer whose magnitude is not standardized.



Given Data / Assumptions:

  • Two small buffers of size 5 are filled with user input via gets (unsafe).
  • strcmp returns <0, 0, or >0 depending on lexicographic order.
  • The exact negative or positive value is not specified by the C standard.
  • Inputs are unknown at question time, so the result varies.


Concept / Approach:
strcmp(a, b) compares the first differing bytes as unsigned char. It returns an integer less than, equal to, or greater than zero. Only the sign matters. Therefore you must not assume -1, 0, or +1 specifically; any negative or positive value can be returned based on character code differences.



Step-by-Step Solution:
User types some line for str1 and str2.strcmp computes the first position where they differ or reaches the terminator.It returns an int whose sign indicates ordering: <0 if str1 < str2, 0 if equal, >0 if str1 > str2.Hence, the exact integer printed is unpredictable beforehand and depends on inputs and character codes.



Verification / Alternative check:
Try various pairs (e.g., "cat" vs "car") across platforms; you may see different negative magnitudes, though the sign is consistent. Also note that using gets invites buffer overflow; safer alternatives are fgets or scanf with width limits.



Why Other Options Are Wrong:
0 / -1 / Always positive: These assert specific results independent of inputs or assume a fixed magnitude.Error: The code compiles; runtime errors happen only if overflow occurs, not guaranteed by the snippet itself.



Common Pitfalls:
Assuming strcmp returns only -1, 0, +1; using gets; neglecting buffer sizes and missing null terminators.



Final Answer:
Unpredictable integer value

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion