0

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?

3
  • 6
    Expected result : Compilation Error - why is that? The code is perfectly valid (except that main() should be main(void)) Commented Apr 5, 2019 at 20:49
  • Which part of this do you not understand? Commented Apr 5, 2019 at 20:49
  • 1
    Why the output is String6 Commented Apr 5, 2019 at 20:52

2 Answers 2

6

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 
Sign up to request clarification or add additional context in comments.

1 Comment

I was waiting for someone to mention the lack of newline character :)
4

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.