Comments in C are used to explain code, improve readability, and make maintenance easier.
They are ignored by the compiler, so they don’t affect the program’s execution.
There are two main types of comments in C:
- Single-line comments: Begins with // and continues to the end of the line.
- Multi-line comments: Begins with /* and ends with */.
Here’s a tutorial covering both types with examples and best practices.
1. Single-Line Comments
Single-line comments start with // and are typically used to explain small parts of code, such as a single line or a variable declaration.
They are convenient for brief, inline explanations.
Example 1: Single-Line Comments for Variable Declarations
#include <stdio.h> int main() { int age = 25; // Age of the user float height = 5.9; // Height in feet printf("Age: %d\n", age); printf("Height: %.1f\n", height); return 0; }
In this example:
- Comments explain each variable's purpose right beside its declaration, keeping the code more understandable.
Example 2: Using Single-Line Comments for Function Explanation
#include <stdio.h> // Main function where the program starts execution int main() { printf("Hello, World!\n"); // Print a greeting message return 0; // Return 0 to indicate successful execution }
2. Multi-Line Comments
Multi-line comments start with /* and end with */.
They are useful for explaining larger sections of code, describing the program's purpose, or temporarily disabling a block of code during debugging.
Example 1: Multi-Line Comment for Program Description
#include <stdio.h> /* * This program calculates the area of a rectangle. * It takes the length and width as inputs and displays the calculated area. */ int main() { int length = 10; // Length of the rectangle int width = 5; // Width of the rectangle int area = length * width; // Area calculation printf("Area of the rectangle: %d\n", area); return 0; }
In this example:
- The multi-line comment at the beginning of the code describes the program's purpose and functionality.
Example 2: Multi-Line Comment to Explain a Block of Code
#include <stdio.h> int main() { int a = 10, b = 20, c; /* * Swapping values of a and b * Temporary variable c is used to store the value of a * before it gets overwritten. */ c = a; a = b; b = c; printf("After swapping: a = %d, b = %d\n", a, b); return 0; }
Here:
- A multi-line comment explains the code block that swaps values between two variables.
3. Using Comments to Disable Code
Comments can also be used to “comment out” sections of code, which means temporarily disabling them during testing or debugging.
Example: Disabling Code with Comments
#include <stdio.h> int main() { int number = 50; // printf("This line is temporarily disabled.\n"); printf("Number: %d\n", number); /* number = 100; printf("Number changed to: %d\n", number); */ return 0; }
In this example:
- The first printf line is temporarily disabled with a single-line comment.
- The second printf line and the assignment are disabled using a multi-line comment. This allows you to easily re-enable the code later by removing the comment symbols.
4. Nested Comments (Trick for Commenting Out Code Blocks)
C does not support true nested comments (you can’t put /* … */ inside another /* … */). However, you can use // within a multi-line comment to mimic nested comments for small cases.
Example: Simulating Nested Comments
#include <stdio.h> int main() { /* * Initializing variables * int x = 10; // Uncomment this line to initialize x * int y = 20; */ printf("This is an example of simulating nested comments.\n"); return 0; }
In this example, using // inside the multi-line comment allows us to ignore specific lines without breaking the main comment block.
5. Best Practices for Using Comments in C
- Keep comments clear and concise: Comments should clarify, not clutter the code.
- Avoid obvious comments: Comments that simply restate the code without adding value are unnecessary (e.g., int a = 5; // Assign 5 to a).
- Use comments to explain the why, not the what: Explain why the code is doing something instead of repeating what it is doing.
- Use consistent formatting: Start each comment with a capital letter, and consider aligning comments in blocks of code for better readability.
Example: Using Meaningful Comments
#include <stdio.h> int main() { int scores[] = {85, 90, 78, 92, 88}; int sum = 0; int count = 5; // Number of elements in scores array // Calculate the sum of all scores for (int i = 0; i < count; i++) { sum += scores[i]; } // Calculate average score and print it float average = (float)sum / count; printf("Average score: %.2f\n", average); return 0; }
In this example:
- Each comment clarifies the intention and purpose of the code rather than stating obvious facts.
6. Documenting Functions Using Comments
When writing functions, it’s helpful to document them with comments explaining parameters, return values, and purpose.
Example: Documenting a Function
#include <stdio.h> /* * Function: add * ---------------------------- * Adds two integers and returns the result. * * a: First integer * b: Second integer * * returns: Sum of a and b */ int add(int a, int b) { return a + b; } int main() { int result = add(5, 7); printf("Result of addition: %d\n", result); return 0; }
In this example:
- The function add is documented with a clear description of its parameters, behavior, and return value, making it easier to understand and use.
Summary Table
Type of Comment | Syntax | Use for |
---|---|---|
Single-Line | // Comment here | Quick explanations for single lines of code |
Multi-Line | /* Comment here */ | Explaining code blocks or the purpose of the program |
Temporary Code Disable | // or /* */ | Disabling code during testing or debugging |
This tutorial provides an understanding of comments in C, allowing you to use them to make your code more readable and maintainable.