Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of printf() function in C

Tags:

c

The printf() function will return the number of characters printed. But in the code below why is it printing 5.

int a=1000; printf("%d",printf("\n%d",a)); 

It prints "1000" once and a space, so altogether we have 2 characters.

It should output "1000 2". But its outputting "1000 5".

like image 926
Angus Avatar asked Aug 14 '11 08:08

Angus


People also ask

What value is returned by printf () and scanf () functions?

printf() - printf() returns the number of characters successfully written on the output. It is used to simply print data in the output. scanf() - It returns the number of data items that have been entered successfully.

What is the return value of scanf in C?

scanf returns EOF if end of file (or an input error) occurs before any values are stored. If any values are stored, it returns the number of items stored; that is, it returns the number of times a value is assigned by one of the scanf argument pointers.

What is the value of printf?

printf() returns total no. of character printed on console, you pass 1000; so first inner printf() function will work and print 1000,and here no. of character is 4.

Why does printf return a value?

1) Return type and value of printf function h, it is used to display messages as well as values on the standard output device (monitor). printf returns an integer value, which is the total number of printed characters. For example: if you are printing "Hello" using printf, printf will return 5.


2 Answers

The number of characters output is 5. 1000 is four characters. \n is one character.

printf doesn't return the number of "items" output like the scanf family of functions do for input. It returns the actual character count.

like image 56
Mat Avatar answered Oct 06 '22 18:10

Mat


The inner call happens first, prints 5 characters (\n, 1, 0, 0, 0) and returns 5.

The outer call then happens, and prints the 5 that was returned by the inner call.

like image 28
RichieHindle Avatar answered Oct 06 '22 19:10

RichieHindle