简体   繁体   English

printf返回什么?

[英]What does printf return?

Today in my interview, the interviewer asked: printf is a function and every function returns something; 今天在我的采访中,采访者问:printf是一个函数,每个函数都返回一些东西; int, void, float, etc. Now what does printf return as it's a function? int,void,float等。现在printf返回什么,因为它是一个函数?

int . int On success, the total number of characters written is returned. 成功时,返回写入的字符总数。 On failure, a negative number is returned. 失败时,返回负数。

See reference here 见这里的参考

Not every function returns something, which is indicated by using void : 并非每个函数都返回一些东西,使用void表示:

void function_returns_nothing(void);

printf is a function (declared in <stdio.h> ) and it returns an int , which is the number of characters outputted. printf是一个函数(在<stdio.h>声明)并返回一个int ,即输出的字符数。 If an error occurs, the number is negative. 如果发生错误,则该数字为负数。

printf() 's reference from MSDN : printf()来自MSDN的参考:

Returns the number of characters printed, or a negative value if an error occurs. 返回打印的字符数,如果发生错误则返回负值。

To add a detail refinement to other fine answers: 要将细节细化添加到其他精细答案:

printf() returns an int , yet does that indicate transmitted vs. printed/written characters? printf()返回一个int ,但是这表示传输打印/写入的字符?

The printf function returns the number of characters transmitted , or a negative value if an output or encoding error occurred. printf函数返回传输的字符数,如果发生输出或编码错误,则返回负值。 C11dr §7.21.6.3 3 (my emphasis) C11dr§7.21.6.33(我的重点)

On success, the number transmitted is returned. 成功时,返回传输的数字。 stdout is typically buffered , so the number of characters printed may not be realized or fail until later. stdout通常是缓冲的 ,因此打印的字符数可能无法实现或直到稍后才会失败。

When int printf() has trouble for various reasons, it returns a negative number. int printf()因各种原因出现问题时,它会返回一个负数。 The number of characters transmitted is not known. 传输的字符数是未知的。

If a following successful fflush(stdout) occurs, then the non-negative value from printf() is certainly the number printed . 如果发生以下成功的fflush(stdout) ,则printf()的非负值肯定是打印的数字。

int transmitted = printf(......);
int flush_retval = fflush(stdout);

int number_certainly_printed = -1; // Unknown
if (transmitted >= 0 && flush_retval == 0) {
  number_certainly_printed = transmitted;
}

Note that "printing" a '\\n' typically flushes stdout , but even that action is not specified. 请注意,“打印” '\\n'通常会刷新stdout ,但是甚至没有指定该操作。
What are the rules of automatic flushing stdout buffer in C? 在C中自动刷新stdout缓冲区的规则是什么?

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

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