eXPerience eXPerience - 3 months ago 16
C Question

Multiple printf() call vs one printf() call with a long string?

Let's say I have one line of

printf()
with a long string:

printf( "line 1\n"
"line 2\n"
"line 3\n"
"line 4\n"
"line 5\n"
"line 6\n"
"line 7\n"
"line 8\n"
"line 9\n.. etc");


What are the costs incurred by this style compared to having multiple
printf()
's for each line?

Would there be a possible stack overflow if the string is too long?

Answer

what are the costs incurred by this style compared to having multiple printf()'s for each line ?

Multiple printf will result in multiple function calls and that's the only overhead.

Would there be a possible stack overflow if the string is too long?

No stack overflow in this case. String literals are stored in read only memory, not in stack memory. When a string is passed to printf then only a pointer to its first element is copied to the stack.

Compiler will treat this multi line string "line 1\n"

"line 2\n"
"line 3\n"
"line 4\n"
"line 5\n"
"line 6\n"
"line 7\n"      
"line 8\n"
"line 9\n.. etc"  

as single string

"line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\n.. etc"  

and this will be stored in read only section of the memory.

But note that (pointed by pmg in a comment) C11 standard section 5.2.4.1 Translation limits says that

The implementation shall be able to translate and execute at least one program that contains at least one instance of every one of the following limits18):
[...]
- 4095 characters in a string literal (after concatenation)
[...]

Comments