Comments in C++
Comments are used to add notes or explanations in your C++ program. They make your code easier to read and understand. Comments are ignored by the compiler, so they do not affect the output of your program.
Adding comments is a good habit, especially when you’re working on large programs or collaborating with other developers.
Single-Line Comment in C++
A single-line comment starts with two forward slashes (//). Everything written after // on the same line is treated as a comment.
Example
// This is a single-line comment
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Multi-Line Comment in C++
If you want to write comments across multiple lines, use /* to begin the comment and */ to end it.
Example
/*
This is a multi-line comment.
It can span multiple lines.
*/
#include <iostream>
using namespace std;
int main() {
cout << "Learning C++ Comments";
return 0;
}
Why Use Comments?
Comments help you write cleaner and more understandable code. They are useful when you want to:
- Explain what a section of code does.
- Make complex logic easier to understand.
- Leave notes for yourself or other developers.
- Temporarily disable a line of code while testing.
Key Points
- Comments are ignored by the compiler.
//is used for single-line comments./* ... */is used for multi-line comments.- Use comments only where they add value.
- Avoid writing unnecessary or obvious comments.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.