CPP Tutorial



C++ COMMENTS


πŸ’¬ Comments in C++

Comments are notes in the source code that are ignored by the compiler. They help programmers explain and document the code for better readability and maintenance.


Types of Comments

  • Single-line comments β€” Used for short explanations or notes.
  • Multi-line comments β€” Used for longer explanations spanning multiple lines.

1. Single-line Comments

// This is a single-line comment
int age = 25;  // Age of the user
    

Use // followed by the comment text. Everything after // on the same line is treated as a comment.

2. Multi-line Comments

/* 
  This is a multi-line comment.
  It can span multiple lines.
*/
int number = 10;
    

Multi-line comments start with /* and end with */. Everything between is ignored by the compiler.


Why Use Comments?

  • Explain the purpose of code sections.
  • Make code easier to understand for others (and your future self!).
  • Help during debugging and maintenance.
  • Temporarily disable code during testing.

Example: Using Comments in a Program

#include <iostream>
using namespace std;

int main() {
  // Declare and initialize variables
  int x = 10;  // Starting value

  /* Increase x by 5
     using addition */
  x = x + 5;

  cout << "Value of x: " << x << endl;  // Output the result

  return 0;  // Indicate successful program termination
}
  

Tips for Writing Good Comments

  • Keep comments clear and concise.
  • Avoid obvious comments that don’t add value.
  • Use comments to explain why something is done, not just what is done.
  • Update comments when code changes.

Try It Yourself!

Add comments to this code snippet to explain each step:

#include <iostream>
using namespace std;

int main() {
  int num1 = 20;
  int num2 = 30;
  int sum = num1 + num2;
  cout << "Sum is: " << sum << endl;
  return 0;
}
  

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review