Breaking line in C/C++ code...

Today my question is a bit C-oriented (although it applies for C++)...
I know line break or new line is '\n', but how do you break line in code?
Like in VB.NET, you can put an underscore '_' at the end of a line and the next line will be continued from the previous...
Likewise, if a specific LOC in my code takes more than one line in the editor, how to tell compiler to continue the line with the next line in the editor?
As far as I am aware, you can just press enter and continue on the next line as normal. C++ ignores whitespace so the line will go on until you terminate it with a semicolon.

The only exception that I'm aware of is string literals (e.g. "foobar"): you can't start a new line in the middle of one of those.
In C/C++ you can put newlines everywhere you can put a space:
1
2
3
4
5
foo ( bar );
// same as:
foo (
bar )
;
You can even insert a newline inside any token if you prepend it with a backslash:
1
2
3
fo\
o ( b\
ar );


In VB statements are delimited by newlines but in C/C++ they are delimited by semicolons so newlines don't matter at all ( unless you are in some preprocessor directive )
Nice! That even works inside string literals. Thanks for the tip - I did not know about that.
C is rather flexible when it comes to how things are arranged.
Normally you don't need to tell the compiler anything, it will just read for more input until the current input construct is satisfied or it meets a semi-colon (;).

What are you trying to do?

It is normally a \ character which is applied to instruct the C Preprocessor that the current definition extends to the line beyond.
The same \ character is also used for continuing string literals.

Examples:

1
2
3
4
5
6
7
8
#define FOO(x) do { \
            /* process x */ \
    } while (0);

/* Or ... */
char *str = "A string... \
which continues to this line\
and this line too.";
Last edited on
For string literals you can also use concatenation:
1
2
3
const char *str = "A string... "
"which continues to this line"
"and this line too."
Is this normal? I could swear I used multiline string literals before without having to treat the line breaks differently.
Like this?
1
2
3
const char *str = "A string... 
which continues to this line
and this line too."
Doesn't work with g++.
The standard defines string literals as this:
string-literal:
    "s-char-sequenceopt"
    L"s-char-sequenceopt"
s-char-sequence:
    s-char
    s-char-sequence s-char
s-char:
    any member of the source character set except
         the double-quote ", backslash \, or new-line character
    escape-sequence
    universal-character-name
So it shouldn't work
Last edited on
Thanks for clearing that up. Well, not that I usually have string literals that are that long anyways :O
Thank you. I received my answer by reading just the first three replies... Cheers. :)
Topic archived. No new replies allowed.