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?
CodePudding user response:
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...
CodePudding user response:
Just the first occurrence of sequence */ ends comment block. It doesn't matter how many occurrences of /* are placed before (any subsequent /* is part of comment, not opening new block). Error depends what you have in code and may be hard to spot. In your case it finds uncommented token cannot which is not valid in that context.
CodePudding user response:
Your code is equivalent to this:
#include <iostream>
cannot nest.
* "cannot nest" is considered source code,
* as is the rest of the program
*/
int main() {
return 0;
}
This is total rubbish and therefore the compiler outputs the corresponding error messages.
