What is the output of the following program?
#include<stdio.h>
void main()
{
printf("hello",printf("world"));
}
What is the output of the following program?
#include<stdio.h>
void main()
{
printf("hello",printf("world"));
}
The printf
function which prints world
runs first as C
cannot execute the first printf
until all of its arguments have been evaluated (as it evaluates extra arguments supplied before the main one) meaning that it waits for 'world'
to be printed before printing 'hello'
.
From the documentation for printf
:
If there are fewer arguments than required by format, the behavior is undefined. If there are more arguments than required by format, the extraneous arguments are evaluated and ignored.
The output of the program is:
worldhello
The argument of the first printf
is:
printf("world")
Since the argument is a function, the function will be called producing word:
word
Then first printf
will print hello
. Those prints together will give you:
worldhello
Try this:
#include<stdio.h>
int main(void)
{
printf(" hello! %d",printf("world"));
return 0;
}
Output:
world hello! 5
If printf
is successful the total number of characters written is returned. On failure, a negative number is returned.