简体   繁体   English

为什么printf在C中返回int而不是size_t

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

Shouldn't the return be of type size_t instead? 不应该返回size_t类型的返回值吗? Because the size of objects in C is of this type, including the string passed to printf . 因为C中对象的大小属于这种类型,包括传递给printf的字符串。

Why printf returns an int in C? 为什么printf在C中返回一个int?
Shouldn't be of type size_t instead? 不应该是size_t类型的?

It could have been, but certainly an early design decision was to accommodate a return value of the negative EOF to indicate error. 它可能是,但肯定早期的设计决定是容纳负EOF的返回值以指示错误。

size_t was something of an afterthought in early design choices. size_t是早期设计选择中的事后想法。 Many functions used int where size_t is used now in those pre-standard days. 许多函数使用int ,其中size_t现在在那些标准前的日子里使用。


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. fprintf()具有环境限制 “任何单个转换可以产生的字符数至少应为4095。”因此,任何尝试输出的打印都可能在INT_MAX/SIZE_MAX关注之前INT_MAX/SIZE_MAX该限制。

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. 你在很大程度上是正确的 - 实际上printf应该返回一个更大的类型,因为它理论上可以输出比可以放入内存的最大对象大小更多的字节,例如printf("%s%s", largest_string, largest_string)或者甚至是使用场宽/精度的更简单的例子。

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. 对于snprintf尤其糟糕,因为snprintf被人为地限制为INT_MAX并且如果您尝试使用它创建更长的字符串,则会被强制返回错误。

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. 没有声明或未指定返回类型的函数的返回类型是int - 隐式int规则。 Some code called printf without bothering with pesky #include <stdio.h> . 有些代码叫做printf而没有烦扰#include <stdio.h>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM