SrcForge

Lesson 5

Single-Line and Multi-Line Comments

Understand C++ comments: single-line (//) and multi-line (/* */), when to use them, and best practices.

Lesson content

Comments in C++ are non-executable notes written for developers. The compiler ignores them, but they improve readability and document intent.

What Are Comments in C++?

Comments are used to explain code, document algorithms, and leave notes for future maintainers without affecting program execution.

Why Comments Are Important

  • Explain complex logic
  • Improve readability
  • Document function behavior
  • Help team collaboration and maintenance

Types of Comments in C++

  • Single-line comments
  • Multi-line comments

Single-Line Comments

Single-line comments start with // and continue to the end of the line. Use them for short explanations and inline notes.

// This is a single-line comment
int sum = a + b; // add two numbers

When to Use Single-Line Comments

  • Clarify a single statement or variable
  • Add quick TODOs or reminders
  • Explain the purpose of the next line of code

Multi-Line Comments

Multi-line comments start with /* and end with */. They are useful for longer explanations or temporarily disabling blocks of code.

/*
  This is a multi-line comment.
  Use it to explain a function or algorithm.
*/
int factorial(int n) {
  // Base case: factorial of 0 is 1
  if (n == 0) return 1;
  // Recursive case: n * factorial(n-1)
  return n * factorial(n - 1);
}

When to Use Multi-Line Comments

  • Document a function or algorithm in detail
  • Provide module-level documentation
  • Temporarily disable a block of code during debugging

Best Practices for Writing Comments

  • Write clear and concise comments
  • Explain why, not what — avoid stating the obvious
  • Keep comments up to date when code changes
  • Use comments to explain intent and design decisions

Common Mistakes to Avoid

  • Writing unnecessary comments that clutter code
  • Leaving outdated comments that mislead readers
  • Explaining obvious code instead of intent
  • Writing unclear or vague comments

Benefits of Properly Commented Code

  • Improved collaboration
  • Easier maintenance
  • Faster onboarding for new developers
  • Reduced debugging time

Frequently Asked Questions

What are comments in C++?

Comments are non-executable notes that explain and document code for developers.

Do comments affect program execution?

No. The compiler ignores comments, so they do not change program behavior.