Comments in C++
Comments are notes in the source code that are ignored by the compiler. Comments serve to explain the purpose, logic, and context of the code to other programmers (or to your future self). Proper use of comments is an important part of writing clean, easy-to-learn code.
Why Are Comments Important?
Without comments, C++ code can be very difficult to understand, especially for complex logic. Comments help with:
- Code documentation — Explaining what the code does and why
- Debugging — Marking parts of the code that have problems
- Collaboration — Making it easier for a team to understand each other's code
- Maintenance — Making it easier to maintain the code in the future
That said, comments should be used wisely — excessive commenting actually makes the code harder to read.
Code Example
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// Calculate the average of an array of numbers
double calculateAverage(const vector<double>& data) {
if (data.empty()) {
return 0.0; // Avoid division by zero
}
double total = 0.0;
// Sum all elements in the vector
for (const auto& score : data) {
total += score;
}
// Divide the total by the number of elements
return total / data.size();
}
int main() {
/*
* This program calculates the average exam score
* of a group of students.
* Data is taken from user input.
*/
vector<double> scores = {85.5, 90.0, 78.5, 92.0, 88.5};
double average = calculateAverage(scores);
cout << "Average score: " << average << endl;
// TODO: Add keyboard input feature
// FIXME: Handling of empty data needs to be fixed
return 0;
}
Code Explanation
Single-Line Comments (//)
A single-line comment starts with // and extends to the end of that line. The compiler ignores all text after // on the same line.
// This is a single-line comment
int x = 10; // A comment can be placed after code
// int y = 20; // This line is commented out and will not be executed
Single-line comments are suitable for:
- A brief explanation of a single line of code
- Temporarily disabling a line of code
- A quick note about a variable or function
Multi-Line Comments (/* */)
A multi-line comment starts with /* and ends with */. All text between those markers is ignored by the compiler, including across several lines.
/*
* This is a multi-line comment.
* Useful for long explanations
* that need several lines.
*/
/* A multi-line comment can also be written on a single line */
Multi-line comments are suitable for:
- Long explanations of an algorithm or logic
- Documentation headers at the top of a file
- Disabling a large block of code
Documentation Comments
Documentation comments are a special comment pattern that can be used by tools such as Doxygen to generate automatic documentation.
/**
* @brief Calculate the average of an array of numbers.
*
* @param data Vector containing the numbers whose average will be calculated.
* @return The average of all elements in the vector.
* Returns 0.0 if the vector is empty.
*/
double calculateAverage(const vector<double>& data) {
// ...
}
/**
* Class to represent a point in a 2D plane.
*/
class Point {
private:
double x; ///< x coordinate
double y; ///< y coordinate
public:
/**
* @brief Constructor for Point.
* @param x Initial x coordinate.
* @param y Initial y coordinate.
*/
Point(double x, double y) : x(x), y(y) {}
/**
* @brief Calculate the distance to another point.
* @param other The target point.
* @return The Euclidean distance between the two points.
*/
double distanceTo(const Point& other) const;
};
Commonly used Doxygen tags:
| Tag | Function |
|---|---|
@brief |
Brief summary |
@param |
Parameter description |
@return |
Return value description |
@see |
Related references |
@note |
Additional note |
@warning |
Warning |
@deprecated |
Marks as deprecated |
@throws |
Exception description |
TODO, FIXME, and HACK Markers
// TODO: Implement filtering feature
// FIXME: Bug in the calculation for negative input
// HACK: Temporary workaround until the library is updated
// BUG: Crashes when the data is empty
// NOTE: This behavior matches specification X
// OPTIMIZE: Consider using a more efficient algorithm
These markers are a convention recognized by many IDEs and editors (including VS Code, CLion, and others), so you can easily search for all TODOs or FIXMEs in a project.
Everyday Use Cases
Scenario: Reading and Understanding Someone Else's Code
Imagine you are asked to fix a bug in the following code:
#include <iostream>
using namespace std;
int main() {
int arr[] = {3, 7, 1, 9, 4, 2, 8, 5, 6};
int n = 9;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Without comments, the code above is hard to understand for anyone not familiar with sorting algorithms. Now compare it with the commented version:
#include <iostream>
using namespace std;
int main() {
// Data to be sorted
int arr[] = {3, 7, 1, 9, 4, 2, 8, 5, 6};
int n = 9;
// Bubble Sort: sort elements from smallest to largest
// Principle: compare two adjacent elements, swap them if out of order
for (int i = 0; i < n - 1; i++) {
// Each iteration, the largest element "floats" to the final position
for (int j = 0; j < n - i - 1; j++) {
// If the current element is greater than the next one, swap them
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print the sorting result
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
The difference is very clear — the second version is much easier to understand thanks to the right comments.
Scenario: Temporarily Disabling Code
Comments are also useful for temporarily disabling code without deleting it:
int main() {
// Code being tested
// cout << "Old version" << endl;
cout << "New version" << endl;
// For debugging, print the value of x
// int x = 42;
// cout << "Debug: x = " << x << endl;
return 0;
}
Guide to Writing Good Comments
What to Do
// ✅ Explain WHY, not WHAT
// Using signed because data from the API can be negative
int balance = 0;
// ✅ Explain complex logic
// Binary search algorithm: divides the array in half
// and searches the half that contains the target
int binarySearch(int arr[], int left, int right, int target) {
// ...
}
// ✅ Mark an edge case
// Handle the case when the user is not registered
if (user.empty()) {
return nullptr;
}
What Does Not Need a Comment
// ❌ A comment that only repeats the code
int count = 0; // initialize count to 0
// ❌ A comment already clear from the variable name
int totalPrice = calculateTotal(price, tax); // calculate the total price
// ❌ An outdated/expired comment
// This function does not take a name parameter (changed 2 years ago)
std::string getName() { return m_name; }
General Rules
- Comments must be relevant — Do not comment on things that are already clear from the code itself
- Keep comments updated — When the code changes, the comments must be updated too
- Do not overdo it — Too many comments actually hurt code readability
- Use consistent spacing — Make sure comments are neat and aligned
- Comment before complex code — Explain the algorithm before the implementation
Comments in Other Programming Languages
| Language | Single Line | Multi-Line | Documentation |
|---|---|---|---|
| C++ | // |
/* */ |
/** */ |
| Python | # |
""" """ |
""" """ |
| Java | // |
/* */ |
/** */ |
| JavaScript | // |
/* */ |
/** */ |
| Go | // |
/* */ |
— |
C++ uses the same comment patterns as Java and JavaScript, so transitioning between these languages is quite easy.
Conclusion
C++ provides three main types of comments: single-line (//), multi-line (/* */), and documentation (/** */ with Doxygen tags). Good comments explain the reasoning and context behind the code, not just repeat what is already written in the code. Use markers such as TODO, FIXME, and HACK to note things that need follow-up. Remember: good comments help readers understand the code faster, while bad comments only add confusion.