C++ Comments
In this page:
Single-Line Comments
Single-line comments start with // and extend to the end of that line, making them ideal for quick, one-off notes right next to the code they describe. The compiler strips them out entirely before compiling, so they have zero effect on your program's performance or behavior.
Example: Single-Line Comments
#include <iostream>
int main() {
// Print the greeting
std::cout << "Hello" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Multi-Line Comments
Multi-line comments open with /* and close with */, letting you comment out or explain a whole block of code that spans several lines. Unlike //, they don't automatically end at a line break, so a missing closing */ will accidentally comment out everything after it until the next one is found.
Example: Multi-Line Comments
#include <iostream>
/*
This block explains the program below.
It can span as many lines as needed.
*/
int main() {
std::cout << "Hello" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Documenting Code
Good comments explain *why* a piece of code exists or why a particular approach was chosen, not just *what* the code does line by line — the code itself already shows that. This kind of context is especially valuable on a shared codebase like cookiescursor.com, where another developer may need to understand your reasoning months later.
Example: Documenting Code
#include <iostream>
int main() {
// Using a cache here because this codebase queries this value
// thousands of times per request -- not just for style.
int cachedValue = 42;
std::cout << cachedValue << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Commenting Out Code
Wrapping a block of code in /* */ is a quick way to temporarily disable it during debugging without deleting it outright, letting you test whether removing that logic fixes a problem. Just remember to un-comment it afterward, or use version control instead if the change might need to stay permanent.
Example: Commenting Out Code
#include <iostream>
int main() {
std::cout << "Active code" << std::endl;
/*
std::cout << "Temporarily disabled while debugging" << std::endl;
*/
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Comment Best Practices
Comments that go stale — describing behavior the code no longer has — are often worse than no comment at all, since they actively mislead the next reader. Keep comments short, update them whenever the logic they describe changes, and avoid comments that just restate obvious code like // increment i above i++.
Example: Comment Best Practices
#include <iostream>
int main() {
int i = 0;
i++; // advance to the next retry attempt (not just "increment i")
std::cout << i << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first: