What does printf return?

后端 未结 4 1207
别那么骄傲
别那么骄傲 2020-12-01 21:18

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 funct

4条回答
  •  孤城傲影
    2020-12-01 21:26

    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?

提交回复
热议问题