C++ Comments
Comments in C++ are used to add annotations or explanations to the code. They are ignored by the compiler and do not affect the execution of the program. There are two types of comments in C++: single-line comments and multi-line comments.
Single Line Comments
Single line comments start with //
and continue to the end of the line. For example:
1// This is a single line comment 2int x = 10;
In the above code, the line // This is a single line comment
is a single line comment and is ignored by the compiler.
Multi-line Comments
Multi-line comments start with /*
and end with */
. For example:
1/* This is a 2 multi-line comment */ 3int x = 10;
In the above code, the text between /*
and */
is a multi-line comment and is ignored by the compiler.
Examples
Here are some examples of comments in C++:
1// This program calculates the area of a circle 2#include <iostream> 3#include <cmath> 4 5int main() 6{ 7 double r; 8 const double pi = 3.14159265; 9 10 // Input the radius 11 cout << "Enter the radius: "; 12 cin >> r; 13 14 // Calculate the area 15 double area = pi * pow(r, 2); 16 17 // Output the result 18 cout << "The area is: " << area << endl; 19 20 return 0; 21}
1/* This program calculates the factorial of a number 2 using a loop */ 3#include <iostream> 4 5int main() 6{ 7 int n; 8 int result = 1; 9 10 // Input a positive integer 11 cout << "Enter a positive integer: "; 12 cin >> n; 13 14 // Calculate the factorial 15 for (int i = 1; i <= n; i++) 16 { 17 result *= i; 18 } 19 20 // Output the result 21 cout << "The factorial of " << n << " is " << result << endl; 22 23 return 0; 24}