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
.
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.
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.
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.
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.
Why printf returns an int in C?
Shouldn't be of typesize_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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With