Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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. Understanding their return values is crucial for error handling and program flow control.
Syntax
int printf(const char *format, ...); int scanf(const char *format, ...);
The printf() Function Return Value
The printf() function returns the number of characters that are printed successfully. If there is an error during output, it returns a negative value.
Example
#include <stdio.h>
int main() {
char str[] = "THE SKY IS BLUE";
int count;
count = printf("%s", str);
printf("\nThe value returned by printf() for the above string is: %d", count);
return 0;
}
THE SKY IS BLUE The value returned by printf() for the above string is: 15
The scanf() Function Return Value
The scanf() function returns the number of input values that are successfully scanned and assigned. If there is an input failure or end-of-file is reached, it returns EOF (typically -1).
Example
#include <stdio.h>
int main() {
int x, y, z;
int result;
printf("Enter three integers: ");
result = scanf("%d %d %d", &x, &y, &z);
printf("The value returned by scanf() function is: %d<br>", result);
printf("x = %d<br>", x);
printf("y = %d<br>", y);
printf("z = %d<br>", z);
return 0;
}
Enter three integers: 7 5 4 The value returned by scanf() function is: 3 x = 7 y = 5 z = 4
Key Points
- printf() returns the number of characters printed (positive) or negative on error.
- scanf() returns the number of successfully read inputs or EOF on failure.
- These return values are useful for error checking and validation in robust programs.
Conclusion
Both printf() and scanf() return integer values that indicate their success or failure. printf() returns character count while scanf() returns the number of successful inputs, making them valuable for program validation.
