C++ Comments
In the C++ programming language, comments are lines of code or text that the compiler ignores and does not execute. The main use of the C++ comments is:
- To document the code and improve code readability. The comments also help other programmers to read and understand your code.
- You can comment the code, preventing execution of the code written in comments.
There are two ways of writing comments in C++ language.
- Single Line Comments
- Multi-line Comments
Single Line Comment
Any text after // on a single line will be ignored and not executed by C++ compiler.
This is an example of single line comment before line of code to explain the code.
// Declare x, and assign value of 2
int x = 2;
This is another example of single line comment at the end of line of code to explain the code. In this case C++ compiler will ignore the text after the //.
int x = 2; // Declare variable x, and assign value of 2
x + 1; // Add value of 1 to x
Following line of code will be ignored by C++ compiler, and from execution as well.
//int x = 2;
Multi-line Comments
Multi-line comments in the code are delimited by /* and */ characters. These multi-line comments can span over multiple lines. The multi-line comments may not be nested.
This example creates a multi-line comments to explain the following code.
/* This line calls the
function myFunc()
*/
myFunc();
You can also use multi-line comment to prevent execution of block of code.
/*
int x = 5
x + 1;
*/