-8
#include <stdio.h>
void main()
{
   printf("%d", printf("%d",printf("Hello world!\n")));
}

Why this gives output as 132 ? hello world is 13 units long.

5
  • 5
    Please use a proper title, don't just put the code in the title. Commented Apr 13, 2018 at 2:37
  • sorry i am new here..I'm changing the title Commented Apr 13, 2018 at 2:38
  • 1
    A proper title... "Can't understand a C Code" is too generic. Commented Apr 13, 2018 at 2:39
  • You're printing characters as integers. What do you expect it to print? The length of the string? Commented Apr 13, 2018 at 2:39
  • @Matt actually, it does not print characters at all. It does print the return value of the printf() function. Commented Apr 13, 2018 at 2:42

2 Answers 2

4

You may be able to see what's happening more clearly if you split the statement into several statements:

int temp1 = printf("Hello world!\n");
int temp2 = printf("%d", temp1);
printf("%d", temp2);

The first printf prints Hello world!\n. Since this is 13 characters, it returns 13.

The second printf prints 13. Since this is 2 characters, it returns 2.

The third printf prints 2.

So the full output will be:

Hello world!
132

It would have been more obvious what's going on if you added more newlines:

printf("%d\n", printf("%d\n",printf("Hello world!\n")));

would print:

Hello world!
13
3
Sign up to request clarification or add additional context in comments.

5 Comments

thank you, i got it. I thought it was one hundred and thirty two.
It would have been less confusing if you put spaces or newlines after the numbers.
actually it's returning Hello world! 13 3 is it for the new line ?
@DhrubaGoswami Yep, you're getting the hang of it now :) I think that last 2 was just a typo here.
@Lundin Not a typo, just forgot that the change would have a secondary effect, I hadn't actually tried it.
2

open man 3 printf and check what it returns

Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).

In your case printf("Hello world!\n") 1st it prints Hello world! and then returns no of printable char which is 13 and again it prints 2 as 13 has 2 char.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.