C Comments: The Complete Beginner’s Guide
Comments in C are used to explain code, make it readable, and debug programs. They are ignored by the compiler, so they don’t affect the program’s output.
Think of comments as notes to yourself or other developers.
Types of Comments in C
C supports two types of comments:
Single-line Comment
Use //
before the comment.
// This is a single-line comment
printf("Hello, World!\n"); // This prints text
Multi-line Comment
Use /* */
to write comments that span multiple lines.
/*
This is a multi-line comment.
It can span multiple lines.
*/
printf("Welcome to C!\n");
Example Program with Comments
#include <stdio.h>
int main() {
// Declare a variable
int age = 25;
/* Display the age */
printf("Age: %d\n", age);
return 0; // End of the program
}
Output:
Age: 25
Why Use Comments in C?
Purpose | Example |
---|---|
Explain complex logic | // Loop to check prime number |
Disable code temporarily | // printf("Debug info"); |
Improve collaboration | /* TODO: Add error handling here */ |
Best Practices for Using Comments
Write comments only where necessary
Keep them short and meaningful
Update comments when code changes
Avoid obvious comments like // Print hello
right above printf("Hello");
Use TODO and FIXME for tracking tasks
Common Mistakes to Avoid
Mistake | Correct Way |
---|---|
Using nested multi-line comments | Not allowed in C |
Writing unnecessary or redundant comments | Only comment when it adds value |
Using ' instead of " in strings | Not a comment issue, but common confusion |
Forgetting to close multi-line comments | Use */ to end the comment |