C Comments
Comments are non-executable parts of the code that provide explanations or annotations. They are ignored by the compiler and are used to improve code readability.
Key Topics
1. Single-line Comments
Single-line comments start with //
and extend to the end of the line.
Example: Using Single-line Comments
// This is a single-line comment
int x = 10; // Initialize x to 10
Code Explanation: Comments explain the purpose of code lines without affecting execution.
2. Multi-line Comments
Multi-line comments are enclosed between /*
and */
.
Example: Using Multi-line Comments
/*
This is a multi-line comment.
It can span multiple lines.
*/
printf("Comments are ignored by the compiler.\n");
Output:
Comments are ignored by the compiler.
Code Explanation: Multi-line comments are useful for longer explanations or commenting out blocks of code.
3. Best Practices in Comments
Effective commenting enhances code maintainability.
- Keep comments clear and concise.
- Update comments when code changes.
- Avoid obvious comments that do not add value.
Best Practices
- Use comments to explain complex logic.
- Document functions with purpose and parameters.
- Consistently format comments throughout the code.
Don'ts
- Don't overuse comments to state the obvious.
- Don't leave outdated comments in the code.
- Don't nest multi-line comments.
Key Takeaways
- Comments improve code readability and maintainability.
- Use single-line comments for brief explanations.
- Use multi-line comments for detailed descriptions.