tags:

views:

76

answers:

4
#include<stdio.h>
int main(void)
{
    int i=1,j=-1;
    if((printf("%d",i))<(printf("%d",j)))
        printf("%d",i);
    else 
        printf("%d",j);
    return 0;
}

As printf() returns the number of characters successfully printed, the condition will be if(1<1) which is false but the if part is executed and the output is 1 -1 1. Why this is happening?

+5  A: 

I think it is rather obvious: '1' is one character, '-1' is two. One is less than two.

Fredrik Mörk
@Fredrik Mörk thank you..
Parixit
+1  A: 

Because printing j prints "-1", that's two characters. so 1<2 is true.

JoshD
@JoshD thnx ..I got it.I was little bit confused..so thnx for the answer.
Parixit
+2  A: 

printf returns the number of characters (not just digits) written.

So printf("%d",-1) will return 2 not 1

Similarly printf("%d",1) will return 1

Making the condition in the if true.

codaddict
+1  A: 

For -1 number of characters printed is 2 hence if condition is satisfied.

Naveen