3

I am reading the Kernigan and Ritchie manual on C.

The following example arises:

printf("hello, world
");

The book states that the C compiler will produce an error message. How exactly does the compiler detect this, and why is this an issue? Shouldn't it just read the newline (presumably at the end of world) as no space?

5
  • 2
    This violates the specs of the language for literal string, so the compiler should produce some error message for failing the compilation.
    – nhahtdh
    Commented Jan 20, 2014 at 23:35
  • How does the compiler detect this? The same way it detects anything. Commented Jan 20, 2014 at 23:36
  • 1
    However you can make multiline strings by adding \ before the new line.
    – sudowoodo
    Commented Jan 20, 2014 at 23:37
  • @CairnO.: you can write a string over more than one line that way, but it does not insert a new line into the string. The only way to make a string which contains newlines is to use \n.
    – rici
    Commented Jan 20, 2014 at 23:52
  • @rici, I suppose I should have clarified, I mean add the slash before the new line in the source not in the sense of \n.
    – sudowoodo
    Commented Jan 20, 2014 at 23:55

3 Answers 3

6

You are not allowed to have a newline in a string literal, we can see this by looking at the grammar from the C99 draft standard section 6.4.5 String literals:

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  

We can see that s-char allows any character except ", \ and new-line.

1

The compiler detects the error because it finds a \n newline (ie, the one right after the d in world) before it has found a " (ie, to match the opening ").

It does this because, as other commenters have said, that is what the specification requires that it do.

1

There's "\n" in the argument. Never hit enter while writing arguments for printf() :)

Not the answer you're looking for? Browse other questions tagged or ask your own question.