C printf return value and empty strings: what does this program print? #include<stdio.h> int main() { int i; char a[] = '\0'; // empty C string if (printf('%s', a)) printf('The string is not empty '); else printf('The string is empty '); return 0; }

Difficulty: Easy

Correct Answer: The string is empty

Explanation:


Introduction / Context:
This item tests knowledge of printf’s return value and behavior with empty strings. printf returns the number of characters printed. When passed an empty string, it prints nothing and returns 0, which is crucial for the if condition in this code.


Given Data / Assumptions:

  • a is initialized to a single '\0', so it is an empty, valid C string.
  • printf('%s', a) prints characters until '\0'; here, it prints zero characters.
  • In C, zero in a conditional is false; nonzero is true.


Concept / Approach:
Evaluating the if condition requires understanding that printf returns the count of printed characters. Printing an empty string prints nothing and returns 0, so the else branch executes.


Step-by-Step Solution:

Compute printf('%s', a): produces no output and returns 0.if (0) is false → execute the else branch.The program prints 'The string is empty' followed by a newline.


Verification / Alternative check:
Change a to 'X'; then printf prints 1 character, returns 1, and the if branch prints 'The string is not empty'.


Why Other Options Are Wrong:

'The string is not empty': would require printf to return nonzero.'No output' or '0': the program always prints one of the messages.Compilation error: code is valid.


Common Pitfalls:
Assuming printf returns true when the call succeeds regardless of printed length; forgetting that empty strings are valid but print nothing.


Final Answer:
The string is empty.

More Questions from Strings

Discussion & Comments

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