Why printf returns int instead of size_t in C

Should the size_t type be returned? Since the size of objects in C is of this type, including the string passed to printf .

+5
source share
3 answers

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

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

size_t was a bit late in the early design options. Many functions used by int , where size_t used now on those pre-standard days.


fprintf() has an environmental limit of "The number of characters that can be obtained with any single conversion must be at least 4095.", so any print that tries to get a long output may encounter this limit before the INT_MAX/SIZE_MAX .

+8
source

You are pretty much right - in fact printf should return a larger type, since it is theoretically possible to output much more bytes than the size of the largest object that can fit in memory, for example. printf("%s%s", largest_string, largest_string) or even more trivial examples using field width / precision.

The reason is just a historical mistake that we're stuck with. This is especially bad with snprintf , which is artificially constrained by INT_MAX and is forced to return an error if you try to create a longer string with it.

+1
source

Then the compilers did not require a function declaration to call the function. The return type of a function without declaration or with an undefined return type of int is an implicit rule of int. Some code called printf does not bother pesky #include <stdio.h> .

0
source

Source: https://habr.com/ru/post/1270974/


All Articles