Search code examples
creturnprintfputs

The return value of puts function in C


I am learning about the functions and the return values, I know that the function puts returns a non-negative integer (I am assuming the number of characters printed) or an EOF for any error, But when will it return zero? I think the minimum number puts can return is 1 (it prints a newline character by default).

In the code attached below. The puts would return 1 and the printf would return 0. I want to know when will puts return zero.

#include <stdio.h>

int main() {
    printf("%d",puts("")); 
    puts("");
    printf("%d",printf(""));
    return 0;
}

Solution

  • The C standard (C99 paragraph 7.19.7.10), which also describes some aspects of the C standard library, says that:

    The puts function returns EOF if a write error occurs; otherwise it returns a nonnegative value.

    Therefore, it is up to the specific library implementation to choose exactly which value to return. As long as the value is not negative, it means the call was successful. A conforming C library implementation can return 0, 12345, the number of characters printed, or a just any random non-negative integer. Therefore, the programmer should not make assumptions about the specific return value.

    The correct way to test for success would then be:

    if (puts(...) != EOF) {...}
    // or
    if (puts(...) >= 0) {...}
    

    If the above tests pass (you enter the if body), then the string was correctly printed.