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
.
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, eg 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.
Back then compilers did not require a function declaration in order to call a function. The return type of a function without declaration or with unspecified return type is int
- the implicit int rule. Some code called printf
without bothering with pesky #include <stdio.h>
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.