C++ Comments
Comments are notes you write inside your code that the compiler ignores. They help you explain what your code does and make it easier to read. This page shows both styles of comments in C++.
Single-line comments
A single-line comment starts with two forward slashes ( // ). Everything after the slashes until the end of that line is ignored by the compiler. Use these for short notes.
Single-line comment
#include <iostream>
using namespace std;
int main() {
// This line prints a greeting
cout << "Hello World!";
return 0;
}Multi-line comments
A multi-line comment starts with /* and ends with */ . Everything between the two markers is ignored, even if it spans several lines. These are handy for longer explanations.
Multi-line comment
#include <iostream>
using namespace std;
int main() {
/* This program shows how
multi-line comments work
in C++ */
cout << "Comments are ignored";
return 0;
}Why use comments?
- To explain the purpose of a tricky piece of code.
- To leave reminders for yourself or other developers.
- To temporarily disable a line of code while testing, without deleting it.
Note: Good comments explain why the code does something, not just what it does. Avoid stating the obvious, and keep comments up to date when you change the code.
Exercise: C++ Comments
How do you write a single-line comment in C++?