Search code examples
c++escapingcomments

What is the exact meaning in C++ of these escape sequences (\n, \t, \v) in comments?


I was reading through the Working Draft of C++ and was surprised when I came across the seemingly simplest feature of programming: Comments! (and even more surprised that I didn't find anything about the behavior of escape sequences in comments!)

Quote from the C++ draft:

If there is a form-feed or a vertical-tab character in such a comment, only whitespace characters shall appear between it and the new-line that terminates the comment; no diagnostic is required.

I struggle in what exactly is meant by this quote.

I came up with this:

// This is a comment\f \tThis is still part of the comment\nThis is not part of the comment

As it seems, escape sequences have influences on comments, so I played around with it for a while but didn't come to a major conclusion.

// This is a comment\nThis is not part of the comment

As they say in the draft:

which terminates immediately before the next new-line character

So I figured, if I just put a newline character in the comment myself, the rest of the comment doesn't get treated as a 'comment'? But it kind of does..? What is the deal with that?


Solution

  • "If there is a form-feed or a vertical-tab character in such a comment, only whitespace characters shall appear between it and the new-line that terminates the comment; no diagnostic is required."

    This talks about literal form-feed and vertical-tab characters, not escape sequences (which are not interpreted in comments).

    A valid comment:

    // comment<a literal vertical-tab><whitespaces...><newline>
    

    Also valid:

    // hello\f\f\f\fworld<newline>
    

    Here's an invalid comment, because the vertical-tab is followed by something else than only whitespace characters before the newline:

    // comment<a literal vertical-tab><whitespaces...>FOO<newline>