C keyword interruptions

Viewed 70

Let's take two examples of having 'stuff' between a keyword:

#include <stdio.h>

int main(void)
{
    printf("OK\n");
    pri\
ntf("OK\n");             // version 1
    pri/**/ntf("Hi");    // version 2
    return 0;
}

That is, having a comment /* ... */ and a \/n. How are these two supposed to be treated, or is it compiler dependent?

2 Answers

I save the code in file a.cpp, then pre-compile the code:

gcc -E a.cpp

The output is:

int main(void)
{
    printf("OK\n");
    printf("OK\n");

    pri ntf("Hi");
    return 0;
}

The first case can pass the compile. but for the second case, gcc will replace /**/ to blank, then compile will fail.

gcc and clang have the same result on this. It's a C standard.

From the C99 translation phases:

The precedence among the syntax rules of translation is specified by the following phases.

  1. Physical source file multibyte characters are mapped, in an implementation- defined manner, to the source character set (introducing new-line characters for end-of-line indicators) if necessary. Trigraph sequences are replaced by corresponding single-character internal representations.
  2. Each instance of a backslash character (\) immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. A source file that is not empty shall end in a new-line character, which shall not be immediately preceded by a backslash character before any such splicing takes place.
  3. The source file is decomposed into preprocessing tokens and sequences of white-space characters (including comments). A source file shall not end in a partial preprocessing token or in a partial comment. Each comment is replaced by one space character. New-line characters are retained. Whether each nonempty sequence of white-space characters other than new-line is retained or replaced by one space character is implementation-defined.
  4. [...]
    pri\
ntf("OK\n");             // version 1

Valid, since it parses as printf("OK\n"); after step 2 above.

    pri/**/ntf("Hi");    // version 2

Invalid, since it parses as pri ntf("Hi"); after step 3 above.

Related