Reputation: 29
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);
}
Expected result : Compilation Error
Output : String6
Why is the output String6
?
Upvotes: 0
Views: 194
Reputation: 137398
Here is the prototype for printf
:
int printf(const char *format, ...);
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");
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);
This then prints 6
(on the same line).
Try running this program:
#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;
}
Output:
String
printf returned: 7
Upvotes: 6
Reputation: 1187
the printf()
function returns the number of character it printed. Since you set int k = printf("String");
, the print function is executing printing out "String" and setting k
equal to 6 since "String" is 6 characters long, then your second call to printf
prints the value of k
which is 6, resulting in the console displaying "String6".
This is perfectly valid C syntax.
Upvotes: 4