0

What is the output of the following program?

#include<stdio.h>

void main()
{
    printf("hello",printf("world"));
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Sandeep
  • 39
  • 6
  • 2
    Actually, looking at [the documentation](http://en.cppreference.com/w/c/io/fprintf) I think it is valid. *If there are more arguments than required by format, the extraneous arguments are evaluated and ignored* – Kevin Mar 07 '18 at 20:48
  • @Kevin It is actually valid and I removed my comment saying it is not.. – Eugene Sh. Mar 07 '18 at 20:49
  • @EugeneSh. so did I :) – Kevin Mar 07 '18 at 20:49
  • 1
    for reference https://stackoverflow.com/questions/3578970/passing-too-many-arguments-to-printf – Eugene Sh. Mar 07 '18 at 20:50
  • 1
    See [What should `main()` return in C and C++](https://stackoverflow.com/questions/204476/) for lots of reasons why `void main()` is dubious. – Jonathan Leffler Mar 07 '18 at 21:43

2 Answers2

2

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'.

Adi219
  • 4,712
  • 2
  • 20
  • 43
2

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.

sg7
  • 6,108
  • 2
  • 32
  • 40