简体   繁体   中英

What does printf return?

Today in my interview, the interviewer asked: printf is a function and every function returns something; int, void, float, etc. Now what does printf return as it's a function?

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 function_returns_nothing(void);

printf is a function (declared in <stdio.h> ) and it returns an int , which is the number of characters outputted. If an error occurs, the number is negative.

printf() 's reference from 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?

The printf function returns the number of characters transmitted , or a negative value if an output or encoding error occurred. C11dr §7.21.6.3 3 (my emphasis)

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.

When int printf() has trouble for various reasons, it returns a negative number. 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 .

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.
What are the rules of automatic flushing stdout buffer in C?

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.

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