C Comments: The Complete Beginner’s Guide
Comments in C are ignored by the compiler but essential for code readability, documentation, debugging, and team collaboration. They help you and others understand what the code does, especially in large projects.
What Are Comments in C?
Comments are non-executable lines in the source code.
Used to describe or explain parts of your code.
Ignored by the compiler during execution.
Types of Comments in C
Type | Syntax Example | Use Case |
---|---|---|
Single-line | // comment text | For short notes |
Multi-line | /* comment block */ | For long explanations or disabling code |
C supports two types of comments:
Single-line Comment
Use //
before the comment.
#include <stdio.h>
int main() {
// Display greeting message
printf("Hello, World!\n");
return 0;
}
Multi-line Comment
Use /* */
to write comments that span multiple lines.
#include <stdio.h>
int main() {
/* This program prints Hello World
and returns 0 to the OS */
printf("Hello, World!\n");
return 0;
}
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 */ |
Common Mistakes
Mistake | Problem |
---|---|
Nesting multi-line comments | Not allowed – causes compile errors |
Forgetting to close a multi-line comment | Will comment out unintended code |
Over-commenting obvious code | Makes code messy |
Best Practices for Using Comments
Tip | Benefit |
---|---|
Use comments to explain “why”, not “what” | Code often shows “what” already |
Keep comments up-to-date | Prevents confusion from outdated notes |
Use single-line for quick notes | Faster to read and cleaner |
Use multi-line for detailed explanations | Useful for documentation and team work |
Commenting Out Code (Debugging Technique)
#include <stdio.h>
int main() {
int a = 5, b = 10;
// printf("Sum = %d\n", a + b); // Temporarily disabled
printf("Hello, debugging!\n");
return 0;
}