Learn how to write comments in C to explain your code
What is this topic?
This guide explains C Comments - Writing Helpful Code Notes in simple terms, what it does, and how to use it in real C programs.
Why We Need It
- It helps you write correct and reliable C code.
- It makes your programs easier to read and maintain.
- It is used in real projects and interviews.
- It reduces common beginner mistakes.
- It builds a strong foundation for advanced topics.
Use Cases
- Building practical C programs step by step.
- Solving real coding tasks with clean logic.
- Preparing for exams, interviews, and projects.
- Understanding and improving existing C code.
What Are Comments?
Comments are notes you add to your code that the computer ignores. They help explain what your code does so that you and others can understand it later.
Important Rule
Comments are for humans, not computers!
Why Use Comments?
1. Explain Complex Code
// Calculate the average of three numbers
int average = (a + b + c) / 3;
2. Remind Yourself Later
// Need to add error checking here later
int result = divide(x, y);
3. Help Other Programmers
// This function was optimized for speed - don't change the algorithm
int fastSort(int array[]) {
// ...
}
4. Disable Code Temporarily
printf("Version 1");
// printf("Version 2"); // Don't use this yet
Single-Line Comments
Use // for comments on one line.
Syntax
// This is a comment
Examples
#include <stdio.h>
int main() {
// This is my first program
printf("Hello, World!");
// End the program
return 0;
}
Comments at the End of Lines
int x = 5; // This is the age variable
printf("%d\n", x); // Print the age
Multi-Line Comments
Use /* */ for comments spanning multiple lines.
Syntax
/* This is a comment
that spans multiple
lines */
Examples
/*
This program calculates
the sum of two numbers
*/
#include <stdio.h>
int main() {
int a = 10;
int b = 20;
/* Add the numbers
and print the result */
printf("Sum: %d\n", a + b);
return 0;
}
Practical Multi-Line Comment
/*
* This function calculates the average of three numbers
* Parameters: three integers a, b, c
* Returns: the average as an integer
*/
int getAverage(int a, int b, int c) {
return (a + b + c) / 3;
}
Comment Best Practices
✓ Good Comments
// Convert temperature from Celsius to Fahrenheit
float fahrenheit = (celsius * 9/5) + 32;
Why: Explains why the code is there.
✗ Bad Comments
// Multiply by 9 and divide by 5, then add 32
float fahrenheit = (celsius * 9/5) + 32;
Why: Just restates what the code already says.
✓ Good: Explains Complex Logic
// Swap values using XOR to save memory
x = x ^ y;
y = x ^ y;
x = x ^ y;
✗ Bad: Over-Commenting Simple Code
int x = 5; // Set x to 5
printf("%d", x); // Print x
Why: Too many obvious comments clutter the code.
Types of Useful Comments
1. Purpose Comments
// Calculate the average grade
float average = total / count;
2. Warning Comments
// WARNING: This array must be freed manually
int *data = malloc(size * sizeof(int));
3. TODO Comments
// TODO: Add input validation for this function
int getValue() {
// ...
}
4. Bug Fix Comments
// Fixed bug where negative numbers caused crashes
if (number < 0) {
number = 0;
}
Real-World Example
Here’s a program with good comments:
#include <stdio.h>
// Function to calculate area of a rectangle
int calculateArea(int length, int width) {
return length * width;
}
int main() {
// Define rectangle dimensions
int length = 10;
int width = 5;
// Calculate and display area
int area = calculateArea(length, width);
printf("Area: %d square units\n", area);
return 0; // Program completed successfully
}
Common Comment Mistakes
Mistake 1: Commenting While Writing is Inefficient
// ✗ Too many obvious comments
x = x + 1; // Increment x
printf("x is %d\n", x); // Print x
Better: Comment only the “why”, not the “what”
// Increment x for next iteration
x = x + 1;
printf("x is %d\n", x);
Mistake 2: Outdated Comments
// ✗ This comment is wrong now
// This function returns the user ID
// (but it actually returns the user name!)
char* getUserInfo() {
return userName;
}
Mistake 3: Comments That Lie
// ✗ Misleading comment
// This function is very fast (but it's actually slow!)
void slowFunction() {
// ... complex code
}
Comment Templates
For Functions
// What does this function do?
// Input parameters: explain each one
// Output: what does it return?
void myFunction(int param) {
// ...
}
Example
// Calculate simple interest
// Inputs: principal (initial amount), rate (percentage), time (years)
// Output: interest earned
float calculateInterest(float principal, float rate, float time) {
return (principal * rate * time) / 100;
}
Code Readability vs Comments
The best code needs fewer comments!
✓ Good (Readable Code)
int calculateTotal(int price, int quantity) {
return price * quantity;
}
✗ Bad (Needs Comments to Understand)
int calc(int p, int q) { // Calculate total (need comment to understand!)
return p * q;
}
Practice
Create a file comments.c:
#include <stdio.h>
// Main program - displays student information
int main() {
// Student information
char name[] = "Alice";
int age = 20;
// Display information
printf("Name: %s\n", name);
printf("Age: %d\n", age);
/* This program demonstrates
the use of comments */
return 0;
}
Navigation
| Previous | Next |
|---|---|
| ← C Output | C Variables → |
Have Questions?
Comment below and we’ll help you! Questions about comments in C? Let us know!