Search code examples
c++ccomments

Nesting comments is not allowed in C/C++. But what do the following errors mean when you try to put one comment pair inside the other?


Consider the following code from 'C++ Primer' by Lippman,

#include <iostream>

/*
* comment pairs /*   */ cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/

int main(){
return 0;
}

On compiling,

 $cl -EHsc .\Program.cc
 Microsoft (R) C/C++ Optimizing Compiler Version 19.30.30706 for x86
 Copyright (C) Microsoft Corporation.  All rights reserved.
 
 Program.cc
 .\Program.cc(4): error C4430: missing type specifier - int assumed. Note: C++ does not 
 support default-int
 .\Program.cc(4): error C2146: syntax error: missing ';' before identifier 'nest'
 .\Program.cc(7): warning C4138: '*/' found outside of comment
 .\Program.cc(10): error C2143: syntax error: missing ';' before '{'
 .\Program.cc(10): error C2447: '{': missing function header (old-style formal list?)

Question 1: What does the following mean from the aforementioned code in the book, ""cannot nest" is considered source code, as is the rest of the program"?

Question 2: What happens under the hood when comments are nested? What do these rather confusing errors produced by the mean?


Solution

  • A comment starts with a /* and ends at */. So in the example, the comment is

    /*
    * comment pairs /*   */
    

    The fact that there is a second /* inside the comment does not "restart" it. It still ends an */.

    So then the compiler tries to interpret cannot nest. as source code. Its best guess seems to be that int cannot could have been a variable declaration, but that the int is missing. And then nest is also a bit wrong, and the errors just continue...