Fundamental Concepts of C++: Code Comments

Comments

Comments are statements that explain the intent of the code. Adding comments in C++ code can help better understand what the program is doing.

The compiler ignores everything in the comments, so this information will not appear in the output and will not be executed by the computer.

Comments that start with two slashes // are called single-line comments. The slashes tell the compiler to ignore everything that follows until the end of the line.

For example:

#include <iostream>using namespace std;int main(){    // Output "Hello world"    cout << "Hello world!";    return 0;}

When the above code is compiled, the statement after // that outputs “Hello world” will be ignored.

Adding comments to code is a good programming practice.

It helps you and other programmers clearly understand the logic of the code implementation.

For example:

The given code outputs “C++ is hard to learn” and “C++ is easy”. Clear comments, only print “C++ is easy”. Use // to comment out a line.

#include <iostream>using namespace std;int main() {        cout << "C++ is easy" << endl;        return 0;}

Multi-line Comments

Multi-line comments start with /* and end with */.

You can place them on the same line or insert one or more lines of text between them.

#include <iostream>using namespace std;int main(){    /* Multi-line comment example    Print "Hello world!" */    cout << "Hello world!"; // Print Hello world!    return 0;}

Comments can be written anywhere and can be repeated any number of times throughout the code.

For example:

Add a block comment (multi-line comment) in C++:

 /*this is a  block/multiline comment in C++ */

Leave a Comment