tags:

views:

726

answers:

3

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?

+28  A: 

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);
James McNellis
just commenting to explain the little-known C fact that whitespace between two strings is concatenation.
Brian Postow
+4  A: 

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").

pmg
Nothing functional here, but a novel idea I've never seen before. I like it, great comment @pmg!
rpj
+5  A: 

C preprocessor offers two options - it can glue adjacent string literals into one, like

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

or use 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);
qrdl
The first has already been suggested, the second suffers from the fact that it breaks if there is any whitespace *after* the '\'; a bug that can be baffling when it occurs.
Clifford
Neither of those two examples have anything at all to do with the C preprocessor.
Dan Moulding
@Dan my cpp seems to understand / (see my edit above). I'm not sure if this is standard behavior.
sigjuice
@Dan While joining adjacent literals may be performed with either preprocessor or compiler (at it last stage before actual compilation), handling line continuation is performed by preprocessor, because otherwise multiline macros cannot be implemented. Also see here - http://gcc.gnu.org/onlinedocs/cpp/Initial-processing.html
qrdl
@sigjuice It is a standard behaviour so your edit is superfluous
qrdl
@qrdl: My bad, you are right about the second one. Line continuation is always done by the preprocessor. Sometimes I need to be reminded that I'm *not* a know-it-all ;) I do still think that in the normal case the compiler joins string literals, though.
Dan Moulding
@qrdl That edit was more of a discussion of one of the points raised by @Dan.
sigjuice