Ashwin Singh
Ashwin Singh

Reputation: 7375

Why this output of this C program?

Program:

   int main( )
    {
    printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));
    return 0;
    }

Output:

5 57 73

I am new to C, I could guess where the 5 57 7 came from, but no idea where the 3 came from. Can someone explain the output?

Upvotes: 0

Views: 149

Answers (4)

TOC
TOC

Reputation: 4446

as you can see here : http://en.wikipedia.org/wiki/Printf_format_string, printf return the number of printed chars, so:

printf("%d",printf("%d %d",5,5)&printf("%d %d",7,7));

is composed of :

printf("%d %d",5,5) return 3 (5 space and 5) and print 5 5

printf("%d %d",7,7) return 3 (7 space and 7) and print 7 7

At this stage we got : 5 57 7

And 3 & 3 = 3, finally you got this output:

5 57 73

Regards.

Upvotes: 0

Eight
Eight

Reputation: 4284

3 is the Bitwise AND of the values returned by two printf.

printf returns the numbers of characters printed. In your case, printf("%d %d",5,5) has printed three characters that are two 5 and one space, similarly printf("%d %d",7,7) is also printing two 7 and one space. Hence both printf is returning 3.

so, 3 is the result of 3 & 3

Upvotes: 2

ouah
ouah

Reputation: 145899

The return value of the printf function is the number of characters transmitted, or a negative value if there is an error.

printf("%d %d",5,5) returns 3 if there is no error

printf("%d %d",7,7) also returns 3 if there is no error

So printf("%d %d",5,5) & printf("%d %d",7,7) is 3 & 3 which is evaluated to 3.

Upvotes: 6

Šimon Tóth
Šimon Tóth

Reputation: 36451

If you apply binary AND to 3 and 3 (which are the return values of both nested printf calls) you get 3 as result.

Note that the code actually contains undefined behaviour, since the order of the nested calls isn't defined.

Upvotes: 6

Related Questions