In C can a long printf statement be broken up into multiple lines?
CPrintfC Problem Overview
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 up. I tried the following but it doesn't 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 break it up?
C Solutions
Solution 1 - C
If you want to break a string literal onto multiple lines, you can concatenate multiple strings together, one on each line, like so:
printf("name: %s\t"
"args: %s\t"
"value %d\t"
"arraysize %d\n",
sp->name,
sp->args,
sp->value,
sp->arraysize);
Solution 2 - C
The C compiler can glue adjacent string literals into one, like
printf("foo: %s "
"bar: %d", foo, bar);
The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):
printf("foo %s \
bar: %d", foo, bar);
Solution 3 - C
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 variations on the theme. The idea is that the printf()
conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").
Solution 4 - C
The de-facto standard way to split up complex functions in C is per argument:
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
sp->name,
sp->args,
sp->value,
sp->arraysize);
Or if you will:
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 shouldn't split up the string, nor should you use \
to break a C line. Such code quickly turns completely unreadable/unmaintainable.
Solution 5 - C
I don't think using one printf
statement to print string literals as seen above is a good programming practice; rather, one can use the piece of code 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);