In C, what is the output of this string-library expression (concatenation + copy + compare)? #include<stdio.h> #include<string.h> int main() { static char str1[] = "dills"; static char str2[20]; static char str3[] = "Daffo"; int i; i = strcmp(strcat(str3, strcpy(str2, str1)), "Daffodills"); printf("%d ", i); return 0; }

Difficulty: Easy

Correct Answer: 0

Explanation:


Introduction / Context:
This C question tests understanding of three core string.h functions used together: strcpy, strcat, and strcmp. You must track destination buffers, returned pointers, and the final comparison result to predict the printed integer.



Given Data / Assumptions:

  • str1 = "dills".
  • str2 is a 20-byte char array (sufficient space).
  • str3 = "Daffo" and is modifiable (array, not literal).
  • All strings are null-terminated, standard C behavior.


Concept / Approach:
strcpy(dest, src) copies src into dest and returns dest. strcat(dest, src) appends src to dest and returns dest. strcmp(a, b) returns 0 if the strings are equal, a positive value if a > b, or a negative value if a < b in lexicographic order.



Step-by-Step Solution:
Step 1: strcpy(str2, str1) → str2 becomes "dills" and returns str2.Step 2: strcat(str3, str2) → str3 becomes "Daffo" + "dills" = "Daffodills".Step 3: strcmp(str3, "Daffodills") → both strings are identical → returns 0.Step 4: printf prints 0.


Verification / Alternative check:
Print intermediate values (puts(str2); puts(str3);) to visually confirm contents before the final strcmp. Since lengths are small and buffers are large enough, there is no overflow.



Why Other Options Are Wrong:
(1), (2), and (4) would require a lexicographic difference; here the strings match exactly. “Implementation-defined result” is inaccurate because the sequence of standard calls is deterministic.



Common Pitfalls:
Confusing the return values of strcpy/strcat with strlen; forgetting that strcat modifies its first argument in place; or assuming strcmp returns boolean values instead of 0/positive/negative integers.



Final Answer:
0

More Questions from Strings

Discussion & Comments

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