Comments:

Comments are used to explain your code and they have nothing to do with the compiler. Compiler ignores the comments and do not consider them as the part of your code. They just make the code readable. The comments do not affect the output of our code.


Types:

There are two types of comments:
  • Single Lined Coments
  • Multi Lined Comments

Single Lined Comment:

If we want to comment a single line in our C++ code, we use single lined comments. To add a single line comment put two forward slashes (//) before that line.

singlelinedcmt.cpp
#include <iostream>
using namespace std;  

int main() {
    //I am printing hello world
    cout << "Hello World!";
    return 0;
}
  

Multi Lined Comment:

If we want to comment multiple lines in our C++ code, we use multi lined comments. To add a multi line comment put /* at the start and */ at the end.

multilinedcmt.cpp
#include <iostream>
using namespace std;

int main() {
    /*I am printing hello world
    This is a multi-lined comment*/
    cout << "Hello World!";
    return 0;
}
  


Why do we use Comments:

  • Documentation: The comments can be used for the purpose of documentation. They can explain the purpose, usage and functioanlity of your code.
  • Divide Code into sections: If your code has different sections and each section is performing a duty, then add comments above each section. This makes your code readable.
  • Temporary Code Removal: If you do not want some lines of code to compile then comment those lines. The commented lines will be ignored by the compiler. If you want the lines back, uncomment them and now you can compile these lines.

  • If you do not want some lines of your code to execute, put them in comments.
  • To comment a line, click on that line to place cursor on that line and then press "Ctrl + /".
  • Comments are just used to increase the readability of your code.