Comments in C++

In C++, comments are used to explain code to readers or to add notes to yourself. These comments are ignored by the compiler and do not affect the program’s functionality. C++ supports two types of comments:

  1. Single-line comments start with two forward slashes (//) and can be used to add comments on a single line.
  2. Multi-line comments start with /* and end with */. They can be used to add comments that span multiple lines.

Comments are a crucial part of programming, as they help other developers understand the code you have written. It is best practice to add comments to your code regularly to ensure that the code remains clear and easy to read. Additionally, comments can be used to document functions and classes, as well as provide instructions on how to use them.

Syntax

// single-line comment

/* 
  multi-line 
  documentation comment 
*/


// comment including parameters
/*
	add function
	@param x integer value to add
    @param y integer value to add
	@return addition of this two parameters
*/
int add(int x, int y) {
    return x + y;
}

Example

#include <iostream>
using namespace std;

/*
	add function
	@param x integer value to add
    @param y integer value to add
	@return addition of this two parameters
*/
int add(int x, int y) {
    return x + y;
}

int main() {
    // Variable declaration and initialization
    double x = 2, y = 4;

    cout << add(x, y); // Output

    // The backslash is a continuation character and will continue the comment to the following line \
    this is a comment too!

    /* 
    The return value is the exit code of the program, 
    the shell can read and use it. The 0 exit code means 
    that the program executed successfully 
    */
    return 0;
}
Output
6