BlogsDope image BlogsDope

Return values of printf and scanf in C

July 3, 2017 C FUNCTION 4798

‘printf’ and ‘scanf’ are two most basic functions of C but do you know they also return values. This post is all about knowing the return values of ‘scanf’ and ‘printf’ of C.

Both ‘printf’ and ‘scanf’ return integer after their execution.

What printf returns


‘printf’ returns the number of characters printed on the console. For example, printf(“ABC”) will return 3 after printing 3 characters (A, B and C), printf(“ABC\n”) will return 4 after printing 4 characters (A, B, C and \n), etc.

Let’s see this working.

#include <stdio.h>
int main ()
{
	printf("%d\n",printf("Hello"));
	printf("%d\n",printf("Hello BlogsDope"));
	printf("%d\n",printf("Hello BlogsDope\n"));
	return 0;
}

Output

Hello5
Hello BlogsDope15
Hello BlogsDope
16

You can see that printf("Hello") printed “Hello” and then returned 5 (after printing 5 characters). Similarly, printf("Hello BlogsDope") and printf("Hello BlogsDope\n") returned 15 and 16 respectively.

What scanf returns


‘scanf’ returns the number of successful inputs taken. For example, scanf(“%d”, &a) will return 1 after taking 1 successful input, scanf(“%d %d”, &a,&b) will return 2 after taking two successful inputs, etc.

#include <stdio.h>
int main ()
{
	int a,b;
	printf("%d\n",scanf("%d", &a));
	printf("%d\n",scanf("%d %d", &a,&b));
	return 0;
}

Output

1
2

You can see that scanf("%d", &a) returned 1 after taking one input and scanf("%d %d", &a,&b) returned 2 after taking two inputs.


Liked the post?
Developer and founder of CodesDope.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).