0
int main (void){
const int y = 99;
printf("%d\n", printf("y = %d", y));
}

This program prints "y = 996", I would like help in understanding.

Firstly,

printf("y = %d", y) prints out y = 99

So the rest of the final expression is:

printf("%d\n", "y = 99");

But this should be invalid as %d expects a number, not a charArray?

garoo
  • 163
  • 1
  • 2
  • 10
  • 5
    No, `printf` _doesn't_ return the string it has printed. The printing itself is just a side-effect. – ForceBru Jan 24 '17 at 17:02
  • 2
    If you had [looked up](http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html) printf, you would have seen what the return value is. – user2357112 Jan 24 '17 at 17:03

3 Answers3

2

The printf function returns the number of bytes printed. That value is what is being passed to the second call.

The inside call prints y = 99 which is 6 characters. So the outer call receives 6 as the second parameter:

printf("%d\n", 6);

So the output is y = 996.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

Let me take a simple example to clear your doubt:

sample :

 void main(void)
    {
    int b=printf("hellow");
    printf("%d",b);
    }

output:

  6

printf("message") is a predefined method which returns "no. of characters present in the message" as the above example.

you code:

int main (void){
const int y = 99;
printf("%d\n", printf("y = %d", y));   
}

note: After printing the message printf() always returns int value which is no of characters because return type of printf() is int type.

step 1: Inner printf() function prints 99 first.

step 2: After execution it returns 6 which is no. of characters in the message.

message is "y = %d"

step 3: 6 is hold by outside printf() function as :-

  printf("%d",6);

So, it gives output combinely :

 996
Shivam Sharma
  • 1,015
  • 11
  • 19
1

While printf will print out a string to stdout, what it returns is an integer that represents the number of characters it printed out.

The nested call to printf, printf("y = %d", y), prints out 99 and returns 6 because the string "y = 99" is 6 characters long, which makes the outer call to printf, which takes the return value of the nested call to printf as an argument, produce the output 6, giving you the final output of 996.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85