C++ Comments
A comment is a note in code that a person writes for other readers. The compiler ignores comments when it builds a program.
A line comment
The comment sits on its own line. The print line below it still runs.
#include <iostream>
int main() {
// Print a greeting
std::cout << "Hello" << std::endl;
return 0;
}A block comment around a statement
The block comment covers one whole statement. That statement does not run.
#include <iostream>
int main() {
/* std::cout << "Hidden" << std::endl; */
std::cout << "Visible" << std::endl;
return 0;
}A trailing comment
The comment follows code on the same line. The code still runs as usual.
#include <iostream>
int main() {
std::cout << "Done" << std::endl; // Mark the end
return 0;
}Example
#include <iostream>
int main() {
// Print the plan for today
std::cout << "Plan for today" << std::endl;
std::cout << "Write one program" << std::endl; // The second line of the plan
return 0;
}Key points
- Use // to start a line comment.
- A line comment runs to the end of its line.
- Use /* to start a block comment and */ to end it.
- A block comment can hide a statement so it does not run.
- A trailing comment sits after code on the same line.
In this example, a line comment sits above the first print line. The first line prints Plan for today. A trailing comment sits after the second print line, and that line prints Write one program.
Note
A comment is for readers, not for the computer.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz C++ Compiler
Exercise
Which marks the start of a line comment?