Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

printf

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?

like image 843
eXPerience Avatar asked Aug 11 '16 12:08

eXPerience


People also ask

What is the purpose of printf() function?

Input/Output The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

How do you separate printf?

The easiest way to break up your string literal is like this: printf( "string1" "string2" "string3", arg1, arg2, arg3, arg4 ); The above works because the compiler combines consecutive string literals.

How do you write printf in two lines?

AFAIK, there's two ways to broke a long printf statement into multiple lines: One is what Viorel_ suggests, concatenate multiple strings together, one on each line. And another way is to use a backslash as the last character, something in this format: printf("part1 \ part2 \ part3");


1 Answers

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 generally 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)
[...]

like image 196
haccks Avatar answered Oct 21 '22 11:10

haccks