Should I be adding comments to my beginner C++ programs?
Asked by
not..a..chance
I'm taking an introductory C++ class, and the assignments are still pretty simple. If I understand what every line does and can write a program that solves the task, is that enough, or should I still be adding comments? I'm especially wondering whether comments are expected even when the code seems self-explanatory.
Answers
Comments are mainly for your future self and anyone else who has to maintain the program. You donโt need exhaustive notes for a tiny exercise, but do document complicated logic, unusual decisions, workarounds, and anything that would be difficult to infer by reading the code. Keep comments accurate, since outdated comments can be more confusing than no comments at all.
Reply to this answer
Try to make the code explain what it does through clear variable, function, and class names. Comments are most useful for explaining why something is done, especially when the reasoning, constraints, edge cases, or side effects arenโt obvious from the code itself. A comment like โincrement counterโ adds little if the code already makes that clear.
Reply to this answer
A good beginner habit is to write a brief plan before implementing a solution, such as the major steps or stages the program will follow. Once the code is written and readable, remove temporary comments that merely repeat the code. For functions intended for other people to use, document their purpose, inputs, outputs, and any important behavior.
Reply to this answer
Check your syllabus or assignment instructions first, because your instructor may specifically require comments. In a class, comments can also show your reasoning and demonstrate that you understand the solution, so a short explanation of the approach is usually worthwhile. You donโt need to comment every single line, though.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Incisor: This also makes maintenance easier. What seems obvious while youโre writing it may be confusing when you return to the project months later.