Why does printf return a value?

前端 未结 6 1834
自闭症患者
自闭症患者 2021-01-11 11:05

I know that printf returns a negative error or number of characters printed on success. Only reason to check this return value is if the execution of program s

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 11:33

    It is mostly for the purposes of error checking. You can make sure that the operation was successful or not using the return value.

    If a non-negative value is returned (indicating the number of characters written) it means the operation was successful. If a negative number is returned there was some error.

    For example,

    #include 
    #include 
    
    int main(void)
    {
        int result = printf("This is a test!");
        if (result > 0)
        {
            printf("%d characters were written!", result);
            return EXIT_SUCCESS;
        }
        else return EXIT_FAILURE;
    }
    

提交回复
热议问题