简体   繁体   中英

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

Using Dev C++ I was doing some fun with C and got this :

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

^^^^ here I thought output would be like "Hello (with spaces) World" but Errors :

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

but when i added a \\ it worked :

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

Without any warnings and errors. What Magic of '\\' is this ? And do any other soccery exists , please let me know .

The backslash has many special meanings, eg escape sequences to represent special characters.

But the special meaning you found is the one of \\ immediatly followed by a newline; which is "ignore me and the newline". For the compiler this solves the problem of encountering a newline in the middle of a string.

The C pre-processor will line splice , so one could have written,

#include <stdio.h>

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

Arguably nicer syntax with long strings. Note that the 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 are very useful in some cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM