Comments in C
Comments are like sticky notes in your code - they're messages you leave for yourself and other programmers to explain what the code does. The best part? The compiler completely ignores them, so they don't affect how your program runs!
Think of comments as your code's documentation. Just like you might write notes in the margins of a textbook, comments help you remember why you wrote certain code and help others understand your logic.
Types of Comments in C
C supports two types of comments:
1. Single-line Comments
- Single-line comments start with
// - Everything after // on that line is treated as a comment
#include <stdio.h>
int main() {
// This is a single-line comment
printf("Hello, World!\n"); // Print message
return 0; // Program executed successfully
}
2. Multi-line Comments
- Multi-line comments start with
/*and end with*/. - Everything between these markers is ignored by the compiler. They're great for longer explanations or temporarily disabling blocks of code.
/*
* This is a multi-line comment
* It can span multiple lines
* Perfect for detailed explanations
*/
#include <stdio.h>
int main() {
/*
This is a multi-line comment.
It can go over several lines.
*/
printf("Hello again!\n");
return 0;
}
When to Use Each Type
| Comment Type | Best Used For |
|---|---|
Single-line (//) | Quick explanations, variable descriptions, end-of-line notes |
Multi-line (/* */) | Detailed explanations, function descriptions, temporarily disabling code blocks |
Tips for Writing Good Comments
- Keep comments short and clear
- Don’t repeat what the code already says
- Use comments to explain why, not just what