I recently encountered with an interview question. I did not understand the behaviour of printf function in this case
#include <stdio.h>
int main() {
int k = printf("String");
printf("%d",k);
}
Run Code Online (Sandbox Code Playgroud)
Expected result : Compilation Error
Output : String6
Why is the output String6?
Here is the prototype for printf:
int printf(const char *format, ...);
Run Code Online (Sandbox Code Playgroud)
We can see that printf returns an int.
The documentation indicates that:
Upon successful return, these functions return the number of characters printed (excluding the null byte used to end output to strings).
You asked why the output is "String6". Well:
printf("String");
Run Code Online (Sandbox Code Playgroud)
This first prints String but does not print a newline character. Since String is 6 characters, printf returns 6, which you store in k:
printf("%d",k);
Run Code Online (Sandbox Code Playgroud)
This then prints 6 (on the same line).
尝试运行此程序:
#include <stdio.h>
int main(void)
{
int bytes_printed = printf("%s\n", "String");
// 7 = 1 + 6
printf("printf returned: %d\n", bytes_printed);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
int printf(const char *format, ...);
Run Code Online (Sandbox Code Playgroud)