Comments in C++ are text that is ignored by the compiler. They can be used to explain the code, make it more readable, or disable code for testing purposes.
There are two types of comments in C++: single-line comments and multi-line comments.
Single-line comments
Single-line comments start with two forward slashes (//) and extend to the end of the line. For example:
// This is a single-line comment.
Multi-line comments
Multi-line comments start with a slash and an asterisk (/*) and end with an asterisk and a slash (*/). For example:
/* This is a multi-line comment.
It can extend over multiple lines.
*/
You can use comments anywhere in your C++ code. For example, you can use them to explain a complex piece of code, to document your code, or to disable code for testing purposes.
Here is an example of how to use comments in C++:
// This function calculates the sum of two numbers.
int add(int a, int b) {
return a + b;
}
// This function prints the value of a variable to the console.
void print(int value) {
std::cout << value << std::endl;
}
int main() {
// Declare two variables.
int x = 10;
int y = 20;
// Calculate the sum of the two variables.
int sum = add(x, y);
// Print the sum to the console.
print(sum);
return 0;
}
In this example, we have used comments to explain the purpose of each function and to document the main() function.
Comments are an important part of C++ programming. They can be used to make your code more readable, maintainable, and efficient.