pyrrhic
pyrrhic

Reputation: 1897

Why exactly does printf not compile?

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?

Upvotes: 3

Views: 547

Answers (3)

GazowanySmalec
GazowanySmalec

Reputation: 33

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

Upvotes: 1

David Wolever
David Wolever

Reputation: 154504

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.

Upvotes: 1

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158489

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.

Upvotes: 6

Related Questions