What does printf return?

后端 未结 4 1183
别那么骄傲
别那么骄傲 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?

    0 讨论(0)
  • 2020-12-01 21:30

    printf()'s reference from MSDN:

    Returns the number of characters printed, or a negative value if an error occurs.

    0 讨论(0)
  • 2020-12-01 21:35

    int. On success, the total number of characters written is returned. On failure, a negative number is returned.

    See reference here

    0 讨论(0)
  • 2020-12-01 21:41

    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.

    0 讨论(0)
提交回复
热议问题