Comments are pieces of code that the compiler discards or ignores or simply does not execute. The purpose of comments is only to allow the programmer to insert some notes or descriptions to enhance readability or understandability of the program.
There are the following two ways to insert comments in C++ programs :
The comments that begin with // are single line comments. The compiler simply ignores everything following // in that same line. Let's take an example program.
// C++ Comments - Single Line Comment #include<iostream.h> #include<conio.h> void main() { clrscr(); // to clear the screen cout<<"Hi!"; // prints Hi! getch(); // holds the output screen } // until user press a key
Here is the sample output of the above C++ program
The block comments, mark the beginning of comment with /* and end with */. That means, everything that falls between /* and */ is considered a comment even though it is spread across many lines. Let's take an example.
/* C++ Comments - Multi Line Comment */ #include<iostream.h> #include<conio.h> void main() { /* to clear the screen */ clrscr(); /* prints Hi! */ cout<<"Hi!"; getch(); /* holds the output screen * until user press a key */ }
This C++ program produces the same output as above.
Let's look at another C++ program using both single line and multi-line or block comments.
/* C++ Comments - Multi Line Comment */ #include<iostream.h> #include<conio.h> void main() { // to clear the screen (single-line comment) clrscr(); // prints Hi! (single-line comment) cout<<"Hi!"; getch(); /* holds the output screen * until user press a key * (multiline or block comment) */ }
Here is the sample output of this C++ program, produces the same output as above C++ programs produced.
In above C++ programs, anything starts from // upto the same line is considered as single-line comment. And anything starts from /* and ends with */ is considered as multiline or block comments.
Here are some more C++ programs listed, that you can go for. These are number-conversion programs in C++: