Code Comments: Types and Best Practices
Learn how to use comments in programming correctly. Explore single-line, multi-line, and documentation comments.
Comments and Their Types
Source code is written for machines, but read by humans. Comments are fragments of a program that are completely ignored by the compiler or interpreter. Their only purpose is to help the programmer understand why a specific piece of code was created and how it works.
Comment
Types of Comments
Most programming languages offer two basic ways to comment, and some add special documentation blocks.
| Cecha | Type | Usage |
|---|---|---|
| Single-line | Short description in one line | // This is a comment |
| Multi-line | Longer explanations, code blocks | /* Comment content */ |
| Documentation | Generating API documentation | /** @param id */ |
When to Use Comments?
A good comment doesn't describe what the code does (that should be clear from variable names), but why it was written that way.
Explaining Intent
Commenting complex algorithms or unusual solutions that are not obvious at first glance.
Commenting the Obvious
Describing simple operations, e.g., i = i + 1; // increment by one. This just clutters the code.
Code as Documentation
Aim for code so clean that comments are only needed in exceptional situations.
Common Mistakes and Pitfalls
Outdated Comments
Leaving 'Dead' Code
Examples in Different Languages
See how comment syntax varies depending on the technology:
// Single-line comment
/*
Multi-line
comment
*/Pro Tips
Use TODOs
Good Commenting Checklist
Before you write a comment, check:
0/4Quiz: Check Your Knowledge
What happens to comments during the program compilation process?
Flow Diagram (Mermaid)
What Next?
- Find out what Javadoc is and how to automatically generate documentation from code.
- Read about Clean Code standards regarding commenting.
- Check how Docstrings work in Python.
- Learn the keyboard shortcut for quick commenting (usually Ctrl + /).
- Solve INF.04 tasks while paying attention to code readability.
You might also like
Relational and Logical Operators: How to Compare Data?
Understand how comparison operators work and how to combine conditions using AND, OR, and NOT. Essential knowledge for control statements.
Conditional Operator: Short-hand if-else in one line
Learn the ternary operator. Find out how to shorten your code and when to use it instead of classic if-else statements.
Mathematical Operators: The Foundation of Computing
Learn basic and advanced mathematical operators. Understand how modulo, incrementation works, and why operator precedence matters.