In this tutorial, you will learn about different types of commenting mechanisms in C++ with the help of examples.
All C++ lines might not need to be executable lines and some can be explanatory lines that help to explain the working of the code and what you intend to achieve or even as a placeholder for the date of creation and the name of the creator. All programming languages have one or the other form of comment lines and C++ allows for Single line and Multiline comments. Any text inside the comment lines is ignored by the compiler.
Single Line Comment
Single line comment in C++ begins with the symbol
// and then the compiler ignores the rest of the line. For example:
cout<<"Hello World" // This is a comment line // cout<<"This line will not get executed"
C++ comments which begin with a
/* and end with a
/* are known as multi-line comments. For example:
/* This is a multi-line comment */ cout<<"Hello World" /* This comment can span over multiple lines */
Nesting of comments
When you are using a
*/ for comment lines, then the
// characters do not affect and hence you can nest the two types of comments together. For example:
/* Multiline comment begins here cout<<"Hello World" // print hello world statement */
Similarly using the other way round,
// This is s single line comment, /* Multiline comment begins here and the comment ends here */
The single-line comment would get be ignored and herbs the multi-line comment never begins for the compiler. This would generate an error and the compiler would not understand the second line.
Purpose of Comment lines
Comment lines are like an accessory that is useful while coding in the sense that when you will revisit the code in the future, then you might not remember all the details of the code but after reading through the comment lines, you will be able to remember the purpose and why you coded that part.
Some comments just plainly explain the working of a line or the work of the lines below it. They can also be used to provide a manual on how to use the code or how to easily modify and understand it by another person who was not involved with the development of the code. This helps other developers to work on the work of other people and improve it.
Some developers even like to leave the license information, date of creation, and their name in the form of comments in the code. So that when other people view it, they get to know properly how to redistribute the code and who was the original creator of the code.