是否需要在C中给出printf()?

use*_*782 1 c

我正在阅读Brian Kernighan和Dennis Ritchie撰写的"The C Programming Language"一书(第2版,由PHI出版).在第一篇1.1入门第一章A教程简介,第7页,他们说必须\n在printf()参数中使用,否则C编译会产生错误信息.但是当我\n在printf()中编译程序时,它没问题.我没有看到任何错误消息.我正在使用Dev-C便携式"MinGW GCC 4.6.2 32位"编译器.

为什么我没有收到错误消息?

yel*_*hil 9

以下是K&R第二版第7页的相关段落:

您必须使用\nprintf参数中包含换行符; 如果你尝试类似的东西

 printf("hello, world
 ");
Run Code Online (Sandbox Code Playgroud)

C编译器将产生错误消息.

这意味着您无法在带引号的字符串中嵌入文字换行符.

但是,下面的任何一行都可以:

printf("hello, world");   /* does not print a newline */
printf("hello, world\n"); /* prints a newline */
Run Code Online (Sandbox Code Playgroud)

上面的所有文字都说你不能在源代码中包含跨越多行的带引号的字符串.

您还可以使用反斜杠转义换行符.C预处理器将删除反斜杠和换行符,因此以下两个语句是等效的:

printf("hello, world\
");
printf("hello, world");
Run Code Online (Sandbox Code Playgroud)

如果你有很多文本,你可以将多个引用的字符串放在一起,或者用空格分隔,编译器会为你加入它们:

printf("hello, world\n"
       "this is a second line of text\n"
       "but you still need to include backslash-n to break each line\n");
Run Code Online (Sandbox Code Playgroud)

  • @ user31782我不这么认为,但我不清楚哪些问题属于哪里.我不知道为什么这个问题被贬低了. (2认同)