C Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - Find Output of Program (Q.No. 7)
7.
What will be the output of the program?
#include<stdio.h>
int main()
{
    char ch;
    if(ch = printf(""))
        printf("It matters\n");
    else
        printf("It doesn't matters\n");
    return 0;
}
It matters
It doesn't matters
matters
No output
Answer: Option
Explanation:

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

Step 1: if(ch = printf("")) here printf() does not print anything, so it returns '0'(zero).
Step 2: if(ch = 0) here variable ch has the value '0'(zero).
Step 3: if(0) Hence the if condition is not satisfied. So it prints the else statements.
Hence the output is "It doesn't matters".

Note: Compiler shows a warning "possibly incorrect assinment".

Discussion:
18 comments Page 2 of 2.

Amita said:   1 decade ago
Hello. Here in the if condition ch=0, means we are assigning a value to ch, so it will return 1 and should execute if condition. Please do clear my doubt if I am wrong.

Shiva said:   1 decade ago
Hai @all.
we can write == in the if condition. Bhaskar is asking what if we write == in that place.
Then it compares 0 with value in ch, since ch is a garbage value, 99.999999% times we will get else output. In condition ch is zero randomly we will get if statement executed. :)

Ganesh -(Gani) said:   1 decade ago
Mr. Sushant how can a if statement check the condition without == symbol.According to u ...U said that we are simply executing the program..But it is wrng bcoz if the 'if' statement comaparison is wrong then it goes to the 'else' statement, but here there is no comparison takes place. So how can u tell the out put is the statement in the else statement.....?????? ..Ganesh

Priyanka said:   1 decade ago
What Bhaskar said is true because if you want to check the condition one should use '==' operator the program cannot be compiled.

Sushant said:   1 decade ago
@Bhaskar,

Yes you do comparisons by "==", however we are not making a comparison over here. We are simple executing a statement in the if() statement and the output decides the condition to be true ie the result is 0(means false) or the result is >1 (means true)

Bhaskar said:   1 decade ago
Hope, we all knew about in if condition comparison can be done with '==' operator not with single '=' operator. Then how could we get output.

Vaibhav said:   1 decade ago
printf always written length of string that is to be printed hence ch = 0

Rahul said:   1 decade ago
printf("") returns 0 to any variable then
ch=0
if (ch)means if(ch!=0) which is not true anytime so else expression will be printed


Post your comments here:

Your comments will be displayed after verification.