Return values of printf() and scanf() in C


The printf() and scanf() functions are required for output and input respectively in C. Both of these functions are library functions and are defined in the stdio.h header file.

Details about the return values of the printf() and scanf() functions are given as follows −

The printf() function

The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value.

A program that demonstrates this is as follows −

Example

 Live Demo

#include <stdio.h>

int main(){
   char str[] = "THE SKY IS BLUE";

   printf("
The value returned by printf() for the above string is : %d", printf("%s", str));    return 0; }

Output

The output of the above program is as follows −

THE SKY IS BLUE
The value returned by printf() for the above string is : 15

Now let us understand the above program.

First, the string is initialized. Then the string is displayed using printf() as well as the value returned by printf(). The code snippet that shows this is as follows −

char str[] = "THE SKY IS BLUE";

printf("
The value returned by printf() for the above string is : %d", printf("%s", str));

The scanf() function

The scanf() function is used for obtaining the input from the user. It returns the number of input values that are scanned. If there is some input failure or error then it returns EOF (end-of-file).

A program that demonstrates this is as follows −

Example

 Live Demo

#include
int main(){
   int x, y, z;

   printf("The value returned by the scanf() function is : %d",
   scanf("%d%d%d", &x, &y, &z));

   printf("
x = %d", x);    printf("
y = %d", y);    printf("
z = %d", z);    return 0; }

Output

The output of the above program is as follows −

7 5 4
The value returned by the scanf() function is : 3
x = 7
y = 5
z = 2

Now let us understand the above program.

There are 3 int variables i.e. x, y and z. Their values are entered by the user using the scanf() function and the return value of scanf() is printed. The code snippet that shows this is as follows −

int x, y, z;

printf("The value returned by the scanf() function is : %d",
scanf("%d%d%d", &x, &y, &z));

Then the values of x, y and z that were obtained from the user are printed. The code snippet that shows this is as follows −

printf("
x = %d", x); printf("
y = %d", y); printf("
z = %d", z);

Updated on: 26-Jun-2020

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements