C++ Comments
Lesson outline
Introduction to C++ Comments
Comments are non-executable annotations that help humans understand code. The compiler discards them during compilation, so they do not affect program behavior or runtime performance. C++ supports two primary styles - single-line and multi-line - for different documentation needs.
Use comments to clarify intent and design decisions; avoid storing sensitive information in comments since they are not a security mechanism.
Comment markers inside string or character literals are not comments (e.g., "//" inside a string stays part of the string).
Single-Line Comments
Single-line comments begin with two forward slashes (//) and extend to the end of the line. They are useful for short notes or inline explanations.
Multi-Line Comments
For longer notes or temporarily disabling a small block of code, use /* ... */ to create a multi-line comment.
Preprocessor Guards for Large Blocks
For larger sections, prefer conditional compilation so you don't run into nested block-comment issues.
Best Practices
Effective commenting follows these guidelines:
- Explain why rather than what the code does
- Keep comments updated when code changes
- Use consistent formatting and tone
- Avoid restating obvious behavior already clear from the code
- Consider TODO/FIXME tags for actionable follow-ups
Strive for readable code first; use comments to explain intent, assumptions, edge cases, and trade-offs.
Debugging with Comments
During debugging, comments can temporarily disable code paths or mark sections for review.
Documentation Comments
Structured comments can be processed by tools (e.g., Doxygen) to generate API documentation.
These documentation styles are conventions used by tools, not special syntax in the C++ language standard. Use a consistent documentation style across the codebase so generated references remain clear and useful.
Real-World Example
In production code, comments document configuration, intent, and non-obvious behaviors.