在 C 语言中,反斜杠如何连接 printf 字符串?

how Backslash \ joins printf strings when written on separate lines in C?

我在使用 Dev C++ 时用 C 做了一些有趣的事情并得到了这个:

#include<stdio.h>
main()
{
printf("Hello
      world" );
}

^^^^ 在这里我认为输出会像 "Hello (with spaces) World" 但是 错误:

C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c In function 'main':
5   10  C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
5   3   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   8   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] 'world' undeclared (first use in this function)
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Note] each undeclared identifier is reported only once for each function it appears in
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ')' before '}' token
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ';' before '}' token

但是当我添加一个 \ 时它起作用了:

#include<stdio.h>
main()
{ 
printf("Hello \ 
   World" );
}

没有任何警告和错误。 这是什么魔法? 还有其他足球存在吗,请告诉我。

反斜杠有很多特殊含义,例如转义序列来表示特殊字符。

但是您发现的特殊含义是 \ 后面紧跟着一个换行符;即 "ignore me and the newline"。对于编译器,这解决了在字符串中间遇到换行符的问题。

C 预处理器将 line splice,所以可以这样写,

#include <stdio.h>

int main(void) {
    printf("Hello\n"
        "World\n");
    return 0;
}

可以说长字符串的语法更好。请注意 maximum length is still enforced. From a theoretical point-of-view, the C pre-processor is a language unto itself, see a discussion on Turing-completeness. For a practical example, x-macros 在某些情况下非常有用。