Comments
A comment is a note in your code for people to read. The compiler skips comments, so they do not change what the program does.
C++ has two kinds of comments:
#include <iostream>
using namespace std;
int main() {
// This is a one-line comment.
cout << "First" << "\n";
/* This comment can
use many lines. */
cout << "Second" << "\n";
return 0;
}
Output:
First
Second
// starts a comment that goes to the end of the line. /* starts a comment that goes on until */, even over many lines.
What are comments for?
The first use is to explain why the code does something. The code already shows what it does. A good comment adds what the code cannot show:
// Price 40, plus a 5 dollar delivery fee
cout << "Total: " << 45 << "\n";
Output:
Total: 45
Without the comment, a reader sees the number 45 and cannot know where it came from.
Avoid comments that only repeat the code. // print the total above that same line would tell the reader nothing new.
The second use is to turn a line off for a while, without deleting it. Put // in front of the line, and the compiler skips it. Programmers call this commenting out a line:
cout << "Start" << "\n";
// cout << "This line is off" << "\n";
cout << "End" << "\n"; // this line runs
Output:
Start
End
The middle line is still in the file, but it did not run. To turn it back on, remove the //. This helps a lot when you look for a mistake in your program.
The last line shows that a // comment can also go at the end of a line of code. The code before the // still runs.
In the exercise, a program prints a line that was only added to find a mistake. Comment it out, but do not delete it.