Visual Studio Code cannot handle macro replacement correctly

Viewed 25
#include <stdio.h>
#define NEG(x) -x
int main (void) {
    printf ("% d\n", NEG (NEG (1)));
    return 0;
}

Visual Studio Code says that NEG (NEG (1)) expands to --1.

Macro Replacement by Visual Studio Code

If Visual Studio Code were correct, this code should contain a compilation error. In fact, no error will be thrown in compilation process because the C-preprocessor cpp.exe substitutes NEG (NEG (1)) for - -1.

Actual Macro Replacement by C-Preprocessor

Why cannot Visual Studio Code handle macro replacement correctly? Is this a bug of the C/C++ plugin of Visual Studio Code?

1 Answers

Preprocessing does not produce a text file, or even a string of characters. It produces a list of tokens; whitespace is not part of this list. (A space character in a string or character literal is not whitespace; whitespace refers to spaces, tabs and newlines found between tokens.):

(§5.1.1.2 (Translation phases), ¶1.7, emphasis added) White-space characters separating tokens are no longer significant. Each preprocessing token is converted into a token. The resulting tokens are syntactically and semantically analyzed and translated as a translation unit.

In a footnote in the same section, the C standard notes that:

Source files, translation units, and translated translation units need not necessarily be stored as files, nor need there be any one-to-one correspondence between these entities and any external representation

In other words, the C standard doesn't concern itself with how the list of tokens might be visualised, nor does it guarantee that there be a visualization. Some compilers attempt to insert whitespace as required so that the output could be retokenized without loss of information; but nothing says that the external representation be a valid input to the compiler, and sometimes it isn't.

What you see as the result of preprocessing is, therefore, not the result of the preprocessing; it's just a debugging aid.

Related