Comments
- C++ course
- Beginner
- Lesson 5/116
- 3 min
Learn to write single-line (//) and multi-line (/* */) comments in C++.
Comments
Comments are notes for the programmer; the compiler ignores them. C++ has two kinds of comments:
- Single-line comment: starts with
//and runs to the end of the line - Multi-line comment: starts with
/*and ends with*/, spanning several lines
Comments explain code, temporarily disable lines or mark sections. But do not write comments instead of working code; code should explain itself.
Using comments
Comments make code readable. They are especially useful for:
- Explaining complex logic:
// b cannot be zero for division - Adding section headers:
// --- Calculation section --- - Temporarily hiding a line (commenting it out)
Example:
// User score
int score = 90;
/* In this section
the score is computed */With clear names you need fewer comments; comments should explain why, not what.
Practice Add comments and output
Add a // comment, a /* */ comment to the program, and print the message Program ready with std::cout.
Starter code
#include <iostream>
int main() {
return 0;
}Sample solution
#include <iostream>
int main() {
// Information
/* This program is ready */
std::cout << "Program ready" << std::endl;
return 0;
}Expected output
Program ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does a multi-line comment start?
- With /* Correct answer
- With ///
- With //
- With <!--
Explanation: A multi-line comment starts with /* and ends with */.
2 Match the comment types
| Term | Meaning |
|---|---|
// |
Single-line comment |
/* */ |
Multi-line comment |
compiler |
Ignores comments |
section header |
Added via comment |
3 Single-line comment
// Score ____ 90
// Score value: 90
Explanation: 'value:' is an explanatory note inside a comment.