Sunday, December 18, 2022

[FIXED] Why does C not recognize strings across multiple lines?

Issue

(I am very new to C.)

Visual newlines seem to be unimportant in C. For instance:

int i; int j;

is same as

int i;
int j;

and

int k = 0 ;

is same as

int
k
=
0
;

so why is

"hello
hello"

not the same as

"hello hello"

Solution

We can think of a C program as a series of tokens: groups of characters that can't be split up without changing their meaning. Identifiers and keywords are tokens. So are operators like + and -, punctuation marks such as the comma and semicolon, and string literals.

For example, the line

int i; int j;

consists of 6 tokens: int, i, ;, int, j and ;. Most of the time, and particularly in this case, the amount of space (space, tab and newline characters) is not critical. That's why the compiler will treat

int           i
;int
j;

The same.

Writing

"Hello
 Hello"

Is like writing

un signed

and hope that the compiler treat it as

unsigned

Just like space is not allowed between a keyword, newline character is not allowed in a string literal token. But it can be included using the newline escape '\n' when needed.

To write strings across lines use string concatenation method

"Hello"
"Hello"

Although the above method is recommended, you can also use a backslash

"Hello \
 Hello"

With the backslash method, beware of the beginning space in a new line. The string will include everything in that line until it finds a closing quote or another backslash.



Answered By - Abdidier Dribbler
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.