In C, can a long printf expression break into multiple lines?

I have the following statement:

printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", sp->name, sp->args, sp->value, sp->arraysize); 

I want to break it. I tried the following, but that did not work.

 printf("name: %s\t args: %s\t value %d\t arraysize %d\n", sp->name, sp->args, sp->value, sp->arraysize); 

How can I smash it?

+63
c printf
Nov 17 '09 at 21:48
source share
5 answers

If you want to split a string literal into several lines, you can combine several lines together, one for each line, for example:

 printf("name: %s\t" "args: %s\t" "value %d\t" "arraysize %d\n", sp->name, sp->args, sp->value, sp->arraysize); 
+130
Nov 17 '09 at 21:50
source share

Just some other formatting options:

 printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", a, b, c, d); printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", a, b, c, d); printf("name: %s\t" "args: %s\t" "value %d\t" "arraysize %d\n", very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d); 

You can add theme options. The idea is that the printf() conversion functions and the corresponding variables line up "nicely" (for some values, "nicely").

+18
Nov 17 '09 at 22:05
source share

The C compiler can glue adjacent string literals into one, for example

 printf("foo: %s " "bar: %d", foo, bar); 

A preprocessor can use a backslash as the last character of a string, not counting CR (or CR / LF if you're from Windowsland):

 printf("foo %s \ bar: %d", foo, bar); 
+16
Nov 17 '09 at 22:42
source share

I do not think that using a single printf expression to print string literals as shown above is good programming practice; rather, you can use the code snippet below:

 printf("name: %s\t",sp->name); printf("args: %s\t",sp->args); printf("value: %s\t",sp->value); printf("arraysize: %s\t",sp->name); 
+2
Aug 11 '16 at 15:02
source share

The de facto standard way to split complex functions in C into an argument:

 printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n", sp->name, sp->args, sp->value, sp->arraysize); 

Or if you:

 const char format_str[] = "name: %s\targs: %s\tvalue %d\tarraysize %d\n"; ... printf(format_str, sp->name, sp->args, sp->value, sp->arraysize); 

You should not split the line, and you should not use \ to break the line C. Such code quickly turns into completely unreadable / unreachable.

+2
Aug 11 '16 at 15:12
source share



All Articles