在 C 语言中,一个长的 printf 语句可以被分解成多行吗?

我有以下声明:

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

我想打破它。我尝试以下方法,但它不工作。

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

我怎么才能拆散他们呢?

167789 次浏览

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);

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

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);

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);

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.