C++ ยท Chapter 6 of 49

C++ Comments

Comments are notes in the source code that the compiler ignores. C++ supports single-line comments starting with `//` and multi-line comments wrapped in `/* ... */`.

Good comments explain *why* something is done, not just *what* the code does, since the code itself already shows the 'what'.

Single-line comments

Anything after `//` on a line is ignored by the compiler. These are great for short notes next to a line of code.

Multi-line comments

`/* ... */` can span several lines and is often used for file headers, licence notices, or temporarily disabling a block of code.

Example 1 (cpp)
// This prints a greeting
std::cout << "Hi";
Output
Hi

The // comment is ignored during compilation.

Example 2 (cpp)
/* This is a
   multi-line comment */
std::cout << "Done";
Output
Done

Everything between /* and */ is ignored, even across lines.

Key points

  • // starts a single-line comment.
  • /* */ wraps a multi-line comment.
  • Comments are ignored by the compiler.
  • Use comments to explain intent, not obvious syntax.
๐Ÿ’ก Note: Overusing comments to restate obvious code is a code smell โ€” let clear variable names do the talking.

๐Ÿ“ Quick Quiz

1. Which starts a single-line comment?

2. Which wraps a multi-line comment?

3. Comments are: