C++ Comments
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.
// Calculate total with tax
float total = subtotal * 1.15f; // 15% tax rate
Multi-Line Comments
For longer notes or temporarily disabling a small block of code, use /* ... */
to create a multi-line comment.
/*
* This function validates:
* - Email format
* - Password strength
* - Age requirements
*/
bool validateUser(User u) {
// Implementation...
}
Preprocessor Guards for Large Blocks
For larger sections, prefer conditional compilation so you don’t run into nested block-comment issues.
#if 0
legacyCalculate(); // temporarily disabled
#endif
newCalculate(); // active path
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
// Bad: Redundant comment
counter++; // Increment counter
// Good: Valuable explanation
// Apply early-bird discount before deadline
if (isEarlyBird) price *= 0.85;
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.
// Temporarily disable this during testing
// legacyCalculate();
newCalculate(); // Using improved algorithm
Documentation Comments
Structured comments can be processed by tools (e.g., Doxygen) to generate API documentation.
/**
* Calculates body mass index (BMI).
* @param weightKg Weight in kilograms.
* @param heightM Height in meters.
* @return BMI value.
*/
double calculateBMI(double weightKg, double heightM) {
return weightKg / (heightM * heightM);
}
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.
#include <iostream>
/*
* MAIN APPLICATION CONFIGURATION
* ------------------------------
* - Max connections: 100
* - Timeout: 30s
* - Log level: 2 (Warnings+Errors)
*/
const int MAX_CONNECTIONS = 100;
int main() {
// Initialize network components
NetworkManager nm(MAX_CONNECTIONS); // illustrative; assume this exists
// Start processing loop
while (true) {
// Check for new connections
if (nm.hasNewConnection()) {
processConnection(); // Handles authentication
}
}
}