
Comments in C
Understanding how to use comments in C is essential for writing readable and maintainable code.
"Comments in C are ignored by the compiler but help programmers understand and document the code."
What Are Comments in C?
Comments are used to add notes or explanations within the code. They are ignored by the compiler and do not affect program execution.
Types of Comments in C
1. Single-Line Comments
Single-line comments start with //
and extend to the end of the line.
#include <stdio.h>
int main() {
// This is a single-line comment
printf("Hello, World!\n"); // Print message
return 0;
}
2. Multi-Line Comments
Multi-line comments start with /*
and end with */
. They can span multiple lines.
#include <stdio.h>
int main() {
/* This is a multi-line comment
It can span across multiple lines */
printf("Hello, C Programming!\n");
return 0;
}
Why Use Comments?
- Improves Code Readability - Helps other programmers understand the code.
- Debugging - Can be used to temporarily disable parts of the code.
- Code Documentation - Explains complex logic within the code.
Best Practices for Using Comments
Best Practice | Example |
---|---|
Use meaningful comments | // Calculate the area of a rectangle |
Avoid redundant comments | // Declaring an integer (Avoid unnecessary comments) |
Use multi-line comments for detailed explanations | /* This function calculates the sum of two numbers */ |
Example: Using Comments in a C Program
#include <stdio.h>
int main() {
// Declare variables
int a = 10, b = 20;
/* Add two numbers
and store the result in sum */
int sum = a + b;
// Print the result
printf("Sum: %d\n", sum);
return 0;
}
Using comments wisely makes your code easier to understand and maintain! 🚀