Learn how to use comments in C++ with examples. Understand single-line and multi-line comments, why comments are important, and how they improve readability in C++ programs.
Comments are notes written inside a program to explain the code.
Comments are ignored by the compiler, so they do not affect the execution of the program.
Comments help us to:
There are two common types of comments:
A single-line comment is used to write a comment on one line.
It starts with:
//
Everything after // on that line is treated as a comment.
#include <iostream>
using namespace std;
int main() {
// This is a single-line comment
cout << "Hello World";
return 0;
}
Hello World
The compiler ignores:
// This is a single-line comment
int age = 20; // Store student's age
Here:
int age = 20; → actual code// Store student's age → commentA multi-line comment is used when the comment covers more than one line.
It starts with:
/*
and ends with:
*/
#include <iostream>
using namespace std;
int main() {
/*
This program displays
a simple message
on the screen.
*/
cout << "Hello World";
return 0;
}
Hello World
Everything between:
/*
and:
*/
is ignored by the compiler.
| Single-Line Comment | Multi-Line Comment |
|---|---|
| Used for one line | Used for multiple lines |
Starts with // |
Starts with /* |
| Ends at the end of the line | Ends with */ |
Example: // My comment |
Example: /* My comment */ |
#include <iostream>
using namespace std;
int main() {
// Declare two numbers
int a = 10;
int b = 20;
/*
Add the two numbers
and display the result.
*/
int sum = a + b;
cout << sum;
return 0;
}
30
// This is a comment
/*
This is a
multi-line comment
*/
Comments are written for programmers, not for the compiler.
They help make C++ programs clear, readable, and easy to understand.