How to add comments in C++
This tutorial will teach you how to add comments in your C++ program. Comments are used in a program to explain the code. Comments have no real effect on your program. The compiler ignores the comments and does not process it.
Add Comments in C++
There are two types of comment in C++:
- Single line comment
- Multi-line comment
How to add single line comment in C++:
To add single line comment in your program, you can use //. The compiler ignores everything that comes in the line after //.
see the code below.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); //prints Codespeedy return 0; }
The output of the above code will be:
Codespeedy.
Now if we remove //prints Codespeedy, there’ll be no change in the output as you can see here.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); return 0; }
Output:
Codespeedy
How to add a multi-line comment in C++:
To add a multi-line comment in a C++ program, use /* and */.
/* is used where the multi-line comment starts and */ is used where the comment ends. See the code for a better understanding.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); /*It prints Codespeedy.*/ return 0; }
The output of this code is:
Codespeedy.
Here you can see that as soon as the compiler encounters a /* symbol, it ignores everything until it reaches a */ symbol.
Now, if we remove /* and */ symbols and everything between it, It will still print Codespeedy.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); return 0; }
Now the output is:
Codespeedy.
We can use /* and */ for a single line comment as well. See the example code.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); /*prints Codespeedy.*/ return 0; }
Output:
Codespeedy.
Nested Comments:
If you use nested comments in your C++ program, chances are that it might show an error. Let’s take a look at this example.
#include <iostream> using namespace std; int main() { printf("Codespeedy."); /*prints /*nested comment*/ Codespeedy.*/ return 0; }
Now your compiler will throw an error because it does not consider the 9th line ( Codespeedy*/) a comment. The key point here is that the comment starts when it encounters a /* symbol which is in the 6th line and ends as soon as it finds a */ symbol which is in the 8th line of code. Thus the comment ends there and since there is no /* symbol afterwards, the next statement is not considered a comment. Hence an error is thrown by the compiler.
Therefore the use of nested comments should be avoided in C++.
Also read:
Leave a Reply