Contents and Thoughts
Two kinds of comment
There are two kinds of comment in C++, single-line and paired(in CommentsInAddTwoNumbers.cpp
).
Single-line. Start with
//
and end with a newlinePaired: Start with
/*
and end with*/
Paired Comments NO NEST
Paired Comments do not nest. So there should not be another paired comment in a paired comment(like in PairNoNest.cpp
).
Way to ignore blocks when debugging or re-editing the code
As paired comments do not nest, re-editing code with paired comment is a bad idea. You never know where there may be another paired comment, which leads to nested comments.
An feasible way is to turn every line into a single-line comment(like in OneLineToGo.cpp
).
Exercise
Exercise 1-7
Compile a program that has incorrectly nested comments.
Solution
Compile PairNoNest.cpp
and get this
PairsNoNest.cpp:2:28: error: ‘cannot’ does not name a type
- comment pairs /* */ cannot nest.
Exercise 1-8
Indicate which, if any, of the following output statements are legal:
std::cout << "/*";
std::cout << "*/";
std::cout << /* "*/" */;
std::cout << /* "*/" /* "*/" */;
After you’ve predicted what will happen, test your answers by compiling a program with each of these statements. Correct any errors you encounter.
Solution
The *i*th line of code is in the file 1-8-i.cpp
in Exercise Code
The 1st, 2nd and 4th lines are all legal. But line 3rd is illegal. Compiling 1-8-3.cpp
will produce
1-8-3.cpp:5:21: warning: missing terminating ” character
std::cout << /* “/” /;
^
1-8-3.cpp:5:2: error: missing terminating ” character
std::cout << /* “/” /;
^
1-8-3.cpp: In function ‘int main()’:
1-8-3.cpp:6:2: error: expected primary-expression before ‘return’
return 0;
^
Adjusting 3rd tostd::out << /* "*//*" */;
does not work, indicating that <<
must have an operant in the right-hand side.
But adjusting it to std::cout << /* "*/""/**/;
works well(in 1-3-8-Correction.cpp
), though it does nothing.