in Programming in C
694 views
2 votes
2 votes
// C/C++ program to demonstrate return value
// of printf()

#include <stdio.h>
int main()
{
    long int n = 123456789;

    printf("While printing ");
    printf(", the value returned by printf() is : %d",
                                    printf("%ld", n));

    return 0;
}

i think this code needs to print “while printing, the value reuturned by printf() is : 9 123456789”

but this prints “While printing 123456789, the value returned by printf() is : 9”

why this is happens ?
in Programming in C
694 views

1 comment

inner printf evaluated first and gives the output to outer printf.
0
0

2 Answers

3 votes
3 votes

It first prints the first line “While printing” .

Then in the same line it first executing the inner most printf “printf("%ld", n).

So it prints the number “123456789”. 

Then the statement “, the value returned by printf() is :”  is printed.

We know printf return no of character it is printed and the inner printf returned 9 as no of character which print at the end due to the %d .

So the output is 

While printing 123456789, the value returned by printf() is : 9”.

 

4 Comments

Please can you tell why inner printf first executed and

Another question is how printf read it's argument either fron left to right or right to left.

Thanks
0
0

@ykrishnay

as you know “printf” is also a function which has arguments which we pass when we call “printf”.

It is the rule in c- programing that the argument to a function calculated first before the calling of the function.

Here in this problem the inner printf is an argument to outer printf which is an integer which the inner printf return . That’s why inner printf called first to calculate the argument with which outer printf will be called .


Order of evaluation of sub-expression inside a function is undefined expect where it is specifically defined.

example:-

Printf(“%d %d %d”, fun1(),fun2(),fun3()); here the order in which fun1(),fun2(),fun3() will be evaluated is undefined .

https://stackoverflow.com/questions/20952318/explain-this-nested-printf-statement

0
0
edited by
Suppose if printf given like this
{
Int a, b, c;

Printf("%d%d%d" , a, b, c) ;

}

How printf read it's argument even though abc are the variables not the expression s?
0
0
1 vote
1 vote

There are 2 printf() functions in this code fragment:

inner printf()
outer printf()
Firstly, the inner printf() will execute and will print 123456789 and then the outer printf() will execute.

It is to be noted that the printf() returns the number of characters that it prints.
Thus, by executing the inner printf(), we have got 9 (because  123456789 are 9 characters), Now, when the outer printf() is executed, 9 is printed.

the inner call happned first it will print 9 number of character.

This answer is as per myknowledge , kindly Correct me if I am wrong.

Also Practice – C Programming GATE Questions

 

Related questions