Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printf return an int instead of a size_t in C

Tags:

c

printf

Shouldn't the return be of type size_t instead? Because the size of objects in C is of this type, including the string passed to printf.

like image 614
Bite Bytes Avatar asked Aug 17 '17 16:08

Bite Bytes


People also ask

How to use printf to print a size_t in C/C++?

What is the correct way to use printf to print a size_t in C/C++? We should use “%zu” to print the variables of size_t length. We can use “%d” also to print size_t variables, it will not show any error.

How to print an int (integer) in C?

Print an int (integer) in C How to print an integer in C language? A user inputs an integer, and we print it. Input is done using scanf function, and the number is printed on screen using printf.

How many characters does printf () return in C?

Check out our Data Structures in C course to start learning today. Example 2: The printf () function in the code written below returns 9. As ‘123456789’ contains 9 characters.

What is the use of printf () in C++?

printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error Example 1: The printf() function in the code written below returns 6. As ‘CODING’ contains 6 characters. // C/C++ program to demonstrate return value.


2 Answers

Why printf returns an int in C?
Shouldn't be of type size_t instead?

It could have been, but certainly an early design decision was to accommodate a return value of the negative EOF to indicate error.

size_t was something of an afterthought in early design choices. Many functions used int where size_t is used now in those pre-standard days.


fprintf() has an environmental limit "The number of characters that can be produced by any single conversion shall be at least 4095.", so any print that is attempting long output may run into that limit before INT_MAX/SIZE_MAX concerns.

like image 106
chux - Reinstate Monica Avatar answered Sep 20 '22 18:09

chux - Reinstate Monica


You're largely right - actually printf should return a larger type, since it's theoretically possible to output many more bytes than the size of the largest object that can fit in memory, e.g. printf("%s%s", largest_string, largest_string) or even more trivial examples using field widths/precisions.

The reason is just a historical mistake that we're stuck with. It's particularly bad with snprintf, which is artificially limited to INT_MAX and is forced to return an error if you attempt to create a longer string with it.

like image 43
R.. GitHub STOP HELPING ICE Avatar answered Sep 19 '22 18:09

R.. GitHub STOP HELPING ICE