Comments in C++ are ignored by the compiler but are useful for programmers. They are used to annotate code for future reference and can be used to make certain lines of code inactive during testing.
In C++, comments can be written in two ways:
/* comment */
: This is a multi-line comment.// comment
: This is a single-line comment.Comment characters (/*
, */
, and //
) have no special
meaning within a character constant, a string literal, or another comment.
// declaring a variable
int a;
// initializing the variable 'a' with the value 2
a = 2;
/* declaring a variable
to store salary for employees */
int salary = 2000;
int main() {
// This is the main function
/* Initialize variables */
int x = 10;
int y = 20;
// Print the sum of x and y
cout << "Sum: " << (x + y) << endl;
return 0;
}
int main() {
int result = 0;
// result = 10 + 20; // This line is commented out for testing purposes
// Uncomment the line below to perform the addition
// result = 10 + 20;
cout << "Result: " << result << endl;
return 0;
}
// BAD: Redundant comment
int x = 10; // Declare x and initialize to 10
// GOOD: Explain why the value is assigned
int x = 10; // Initializing x to 10 to use as a counter