472,786 Members | 1,417 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,786 software developers and data experts.

how the following printf statement works

hi,

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.

Thanks,

Aditya.
Nov 14 '05 #1
8 2632

"aditya" <ad************@gmail.com> wrote in message
news:2c*************************@posting.google.co m...
hi,

Can anybody please tell me that how the following printf(...)

statement works-

main(){
int d=9;
printf("%d",printf("%d"));
I think you missed out argument d, to the sec printf !!
return 0;
}

The output is 91.

Thanks,

Aditya.


On my system it gives 91 if properly edited

Try including the necessary headers and then exec:

bash-2.02$ cat t12.c

#include <stdio.h>
int main()
{
int d=9;

printf("%d",printf("%d", d));
printf ("\n"); /* Needed for the output to be displayed ! */
return 0;
}
bash-2.02$ gcc -pedantic -Wall -ansi t12.c
bash-2.02$ ./a.exe
91

Initially the inner/second 'printf' prints the value of d == 9, then return
value of inner printf is taken as a argument
to the outer printf, which then prints 1.

From the standard:

4.9.6.3 The printf function

Synopsis

#include <stdio.h>
int printf(const char *format, ...);

Description

The printf function is equivalent to fprintf with the argument
stdout interposed before the arguments to printf .

Returns

--> *The printf function returns the "number of characters transmitted",
or a negative value if an output error occurred.*

So in your case the number of characters transmitted by the sec. printf is
1 (which is '9')
hence you can see the output as "91"

- Ravi
Nov 14 '05 #2
aditya <ad************@gmail.com> scribbled the following:
hi, 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.


This code causes undefined behaviour, so the output might be anything it
wants, including "Your mother was a hamster and your father smelt of
elderberries!". The outer printf() function expects to print an integer
number, and this integer number comes from the return value of the
inner printf(). printf()'s return value is defined to be the number of
bytes it actually managed to print. However, the inner printf()
function also expects to print an integer number, but it is never given
one. This is what causes undefined behaviour, because printf() is now
forced to get the integer number from some undefined place. This might
be the execution stack (if there is one), a random address in memory,
your pet iguana's mind, or whatever else your implementation fancies.
So the answer to your question is "No, it doesn't work".

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"This is a personnel commuter."
- Train driver in Scientific American
Nov 14 '05 #3
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
Nov 14 '05 #4
aditya wrote:
hi,

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.

Only by accident.
/* mha: Please not the changes in your code. The code you posted does
*not* do what you claimed. */
#include <stdio.h> /* mha: A prototype for the variadic
function printf is REQUIRED even in
C89 */

int /* mha: main always returns an int in a
hosted system. Say so. This is
REQUIRED in C99 */
main(void)
{
int d = 9;
#if 0
/* mha: original printf call. Note that the outer one fails to have
portable behavior because it has no end-of-line character for the
last line of output and the inner one has the wrong number of
arguments. That missing argument is why the code doesn't print
the '9' you claim except by accident. */
printf("%d", printf("%d"));
#endif
printf("%d\n", printf("%d", d)); /* mha: new printf */
return 0;
}
Nov 14 '05 #5
Stuart Gerchick <sg*******@bloomberg.net> scribbled the following:
printf("%d",printf("%d")); remember that printf returns the number of characters printed.
printf("%d") prints 9 and returns 1....so the first %d prints the
return value of 1.


printf("%d") does not print 9 and return 1. It's not guaranteed to,
anyway. It might legally print and return anything it wants.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"Make money fast! Don't feed it!"
- Anon
Nov 14 '05 #6
In <cl**********@oravannahka.helsinki.fi> Joona I Palaste <pa*****@cc.helsinki.fi> writes:
Stuart Gerchick <sg*******@bloomberg.net> scribbled the following:
printf("%d",printf("%d"));

remember that printf returns the number of characters printed.
printf("%d") prints 9 and returns 1....so the first %d prints the
return value of 1.


printf("%d") does not print 9 and return 1. It's not guaranteed to,
anyway. It might legally print and return anything it wants.


And this is what it actually does. The 9 is an "accident" happening
under very specific conditions (one stack used for everything, function
arguments pushed on the stack starting with the last, the function
return address pushed after the arguments, the return value either not
allocated on the stack or allocated after all the arguments).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #7
aditya wrote:

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.


It doesn't. Apart from the illegal invocation of main, and the
lack of <stdio> inclusion, the printf statements invoke undefined
behavior. Try:

printf("%d\n", printf("%d ->", 789));

and remember that printf returns the number of chars printed, and
that a functions arguments are evaluated before a function is
called.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #8
Dan Pop <Da*****@cern.ch> scribbled the following:
In <cl**********@oravannahka.helsinki.fi> Joona I Palaste <pa*****@cc.helsinki.fi> writes:
Stuart Gerchick <sg*******@bloomberg.net> scribbled the following:
printf("%d",printf("%d"));
remember that printf returns the number of characters printed.
printf("%d") prints 9 and returns 1....so the first %d prints the
return value of 1.


printf("%d") does not print 9 and return 1. It's not guaranteed to,
anyway. It might legally print and return anything it wants.

And this is what it actually does. The 9 is an "accident" happening
under very specific conditions (one stack used for everything, function
arguments pushed on the stack starting with the last, the function
return address pushed after the arguments, the return value either not
allocated on the stack or allocated after all the arguments).


Yes, I agree completely. That's why I said "it's not guaranteed to,
anyway".

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"To err is human. To really louse things up takes a computer."
- Anon
Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Adi | last post by:
hi guys, i have a weird problem with printf statement. I have a function which just prints a string literal. In my program this function will be called > 2000 times. I get a segmentation fault...
4
by: ben | last post by:
why is it, in the below code, when there's a printf statement (the one commented with /* ****** */) the final for loop prints out fine, but without the commented with stars printf statement...
7
by: ssantamariagarcia | last post by:
I have found a problem while using a while statement and a linked list. I had never met this matter before....and I am wondering that if you have , please tell me what it is wrong. I am...
7
by: Martin Jørgensen | last post by:
Hi, Perhaps a stupid question but I wonder if this isn't possible using C: printf("\nOr push <enter> for default (which is theta=%ld)%s", theta, ": "); It would be nicer to have it on one...
4
by: pai | last post by:
Hi , Can any one tell me how this statement of printf is behaving . how the last digit is printed int a=2,b=4,c=7; printf("%d",printf("%d %d:",a,b)); //answer to this was 2 4:3
51
by: Spidey | last post by:
for(;0;) printf("hello"); even the condition s wrong i get a hello printed on the screen y s this happening
7
by: Avaenuha | last post by:
Hi, It appears my program can't get past a particular printf() statement. Code excerpt: printf("Sales Report\n--------------"); printf("Testing code - pre loop entry"); while(category !=...
16
by: Ravi | last post by:
main() { float a = 5.375; char *p; int i; p = (char*)&a; for(i=0;i<=3;i++) printf("%02x",(unsigned char)p); } the above code gives the binary representation of a.
10
by: saipathakota | last post by:
how the following two code parts same: #include <stdio.h> void main () { char i = NULL; char &q = i;
0
by: Rina0 | last post by:
Cybersecurity engineering is a specialized field that focuses on the design, development, and implementation of systems, processes, and technologies that protect against cyber threats and...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.