In C programming, comments are used to annotate the code and explain the logic behind it. Comments are ignored by the compiler, so they do not affect the execution of the program. There are two types of comments in C:
1. Single-line Comments
A single-line comment starts with //
. Everything after //
on that line is considered a comment and will not be executed.
Example:
// This is a single-line comment
int x = 5; // This is also a comment after code
2. Multi-line Comments
A multi-line comment starts with /*
and ends with */
. This type of comment can span multiple lines.
Example:
/* This is a multi-line comment
that spans multiple lines */
int y = 10;
Usage
Comments are helpful in explaining the purpose of code, making it easier to understand for others (or for yourself when revisiting your code after some time). They can be used to describe the functionality, assumptions, and logic behind your code.
Example:
#include <stdio.h>
int main() {
// Initialize variables
int a = 10; // Set a to 10
int b = 20; // Set b to 20
// Calculate sum
int sum = a + b;
printf("Sum: %d\n", sum); // Print the sum
return 0;
}
Note: It’s important to avoid over-commenting, especially with obvious or trivial code. The goal is to make the code more readable and maintainable.