Comments in C
Comments are notes written inside a program to explain the code.
They are ignored by the compiler and do not affect program execution.
Why Are Comments Important?
- Help in understanding code later
- Useful when multiple developers work on same project
- Explain complex logic in simple words
- Help beginners organize and document their code
Types of Comments in C
1. Single-line Comment 2. Multi-line Comment
1. Single-line Comment
Begins with // and continues till end of line.
#include <stdio.h>
int main() {
int a = 10; // this is a single-line comment
printf("Value: %d", a);
return 0;
}
2. Multi-line Comment
Starts with /* and ends with */.
Used for long explanations.
#include <stdio.h>
int main() {
/* This is a multi-line comment.
It can span across multiple lines.
Used to explain big concepts. */
printf("Hello World!");
return 0;
}
Where Should You Use Comments?
- Before major logic blocks
- To explain purpose of a variable
- To describe function usage
- To label different sections of code
Practical Example 1 – Explaining Code
#include <stdio.h>
int main() {
int n = 5;
// Printing numbers 1 to 5
for(int i = 1; i <= n; i++) {
printf("%d ", i);
}
return 0;
}
Practical Example 2 – Block-wise Explanation
#include <stdio.h>
int main() {
/* Declare variables */
int x = 10;
int y = 20;
/* Calculate sum */
int sum = x + y;
/* Display output */
printf("Sum = %d", sum);
return 0;
}
Practical Example 3 – Disabling Code Using Comments
#include <stdio.h>
int main() {
int x = 10, y = 5;
// printf("This line is disabled temporarily\n");
printf("Active Output: %d", x + y);
return 0;
}
Practical Example 4 – Header Documentation
/*
Program: Adding Two Numbers
Author : Sourav
Date : 2025-01-01
*/
#include <stdio.h>
int main() {
int a = 10, b = 20;
printf("Sum = %d", a + b);
return 0;
}
Best Practices for Comments
- Write meaningful comments
- Do not over-comment obvious code
- Update comments when code changes
- Use comments to explain "why", not "what"
Practice Questions
- What are comments? Why are they used?
- Difference between single-line and multi-line comments.
- Write a program with both types of comments.
- Explain 4 best practices for comments.
- Write comments for a program that calculates the area of a rectangle.
Practice Task
Write a program to print your name and course using
two single-line comments and one multi-line comment.