C Programming - Strings - Discussion


What will be the output of the program ?


int main()
    int i;
    char a[] = "\0";
    if(printf("%s", a))
        printf("The string is not empty\n");
        printf("The string is empty\n");
    return 0;

[A]. The string is not empty
[B]. The string is empty
[C]. No output
[D]. 0

Answer: Option B


The function printf() returns the number of charecters printed on the console.

Step 1: char a[] = '\0'; The variable a is declared as an array of characters and it initialized with "\0". It denotes that the string is empty.

Step 2: if(printf("%s", a)) The printf() statement does not print anything, so it returns '0'(zero). Hence the if condition is failed.

In the else part it prints "The string is empty".

John Doe said: (Apr 17, 2012)  
I believe the explanation is not the best one.
printf returns the number of bytes printed not including the trailing '\0' used to end output to strings.Therefore the return will be 0 and the condition is false.

Ask said: (Sep 24, 2015)  
I am not agree with the @John. Output would be A.

Santhosh said: (Nov 4, 2016)  
Output will be A because it will return 1.

Nads said: (Aug 22, 2017)  
Answer is A because it is in double quotes not single.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.