In <2c*************************@posting.google.com>
ad************@gmail.com (aditya) writes:
Can anybody please tell me that how the following printf(...)
statement works-
main(){
int d=9;
printf("%d",printf("%d"));
return 0;
}
The output is 91.
Not on the system I've tried it:
mentor:~/tmp 12> cat test.c
main(){
int d=9;
printf("%d",printf("%d"));
return 0;
}
mentor:~/tmp 13> cc test.c
mentor:~/tmp 14> ./a.out
-133609449mentor:~/tmp 15> gcc test.c
mentor:~/tmp 16> ./a.out
665605mentor:~/tmp 17>
This piece of junk invokes undefined behaviour twice and doesn't even
generate a properly terminated line of output (hence my shell prompt gets
appended to your program's output).
You CANNOT use printf without declaring it first (it's a variadic
function) and no printf call can supply fewer arguments than expected
by its format string.
So, let's turn it first into a program with a well defined output:
#include <stdio.h>
int main()
{
int d = 9;
printf("%d\n", printf("%d", d));
return 0;
}
This program outputs 91 by design and not by pure accident. So, the
output is the same, no matter where you compile and execute it.
The inner printf gets executed first. It displays the value of d, which
is 9 and returns the number of displayed characters (1, in this case) to
its caller. The caller, which is the outer printf call, displays this
value and terminates the line with a newline character.
It is possible to explain why the original program displays 91 on the
vanilla x86 implementation, but you're not going to learn anything
about the C language from that explanation. It is an instructive
exercise for people interested in how x86 C compilers work, however,
but, since it's off topic in this newsgroup, anyway, I won't bother
writing the explanation. It involves the way automatic variables are
allocated and function arguments are passed.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de
Currently looking for a job in the European Union