Comments
Overview
When you write a complex algorithm, it might make perfect sense today. But when you (or a teammate) return to that code six months later, it will look like an alien language. Comments are human-readable text injected directly into the source code that the C++ Compiler completely ignores.
Beyond just explaining logic, comments are the ultimate debugging tool. If your program is crashing, you can 'comment out' large chunks of code to physically hide them from the compiler, allowing you to isolate exactly which line is causing the failure without having to delete the code.
Syntax
// 1. SINGLE-LINE COMMENT
// Used for quick, short explanations
int health = 100; // Starting player health
/*
2. MULTI-LINE COMMENT
Used for massive block explanations,
API documentation, or copyright notices.
*/
int stamina = 50;Common Pitfalls
- Writing 'What' instead of 'Why'. Writing
x = x + 1; // Adds 1 to xis useless and clutters the screen. Good comments explain the architectural reasoning:x = x + 1; // Compensate for the 0-indexed array offset. - Attempting to nest multi-line comments. If you write
/* Outer /* Inner */ */, the C++ compiler will see the very first*/and assume the entire comment block has ended, causing massive syntax errors on the remaining text.
Interview Questions
The Preprocessor physically strips every single comment out of the source code before the Compiler even sees it. Comments have absolutely zero impact on the final executable size or runtime performance.
Real-World Example
Using multi-line comments to instantly disable a broken feature during intense debugging.
int main() {
launchGame();
/*
TODO: The multiplayer connection is crashing the server.
Disabling it temporarily until the networking bug is fixed.
connectToServer();
syncPlayers();
*/
return 0;
}Check Your Knowledge
Test your understanding of Comments with these quick questions.