Search code examples
ccommentsc-preprocessorbackslash

C preprocessor: line continuation: why exactly comment is not allowed after backslash character ('\')?


Valid code:

#define M xxx\
yyy

Not valid code:

#define M xxx\/*comment*/
yyy

#define M xxx\//comment
yyy

Questions:

  1. Why comment is not allowed after backslash character (\)?
  2. What the standard says?

UPD. Extra question:

  1. What is the motivation / reason / argumentation behind the requirement that (in order to achieve splicing of physical source lines) backslash character (\) must immediately follow by a new-line character? What is the obstacle to allow comments (or spaces) after the backslash character (\)?

Solution

  • There is actually a reason why backslash-newlines are processed before comments are removed. It's the same reason why backslash-newlines are entirely removed, instead of being replaced with (virtual) horizontal whitespace, as comments are. It's a ridiculous reason, but it's the official reason. It's so you can mechanically force-fit C code with long lines onto punched cards, by inserting backslash-newline at column 79 no matter what that happens to divide:

    static int cp_old_stat(struct kstat *stat, struct __old_kernel_stat __user * st\
    atbuf)
    {
            static int warncount = 5;
            struct __old_kernel_stat tmp;
    
            if (warncount > 0) {
                    warncount--;
                    printk(KERN_WARNING "VFS: Warning: %s using old stat() call. Re\
    compile your binary.\n",
    

    (this is the first chunk of C I found on my hard drive that actually had lines that wouldn't fit on punched cards)

    For this to work as intended, backslash-newline has to be able to split a /* or a */, like

    /* this comment just so happens to be exactly 80 characters wide at the close *\
    /
    

    And you can't have it both ways: if comments were to be removed before processing backslash-newline, then backslash-newline could not affect comment boundaries; conversely, if backslash-newline is to be processed first, then comments can't appear between the backslash and the newline.

    (I Am Not Making This Up™: C99 Rationale section 5.1.1.2 paragraph 30 reads

    A backslash immediately before a newline has long been used to continue string literals, as well as preprocessing command lines. In the interest of easing machine generation of C, and of transporting code to machines with restrictive physical line lengths, the C89 Committee generalized this mechanism to permit any token to be continued by interposing a backslash/newline sequence.

    Emphasis in original. Sorry, I don't know of any non-PDF version of this document.)