Main explanation with examples:
In C, there are two main types of comments: single-line comments and multi-line comments. Single-line comments start with //
and end at the end of the line, while multi-line comments are enclosed between /*
and */
.
// This is an example of a single-line comment
/*
This is a
multi-line comment
*/
Key terminology:
1. Single-line Comment: A comment that spans only one line.
2. Multi-line Comment: A comment that spans multiple lines, enclosed between /*
and */
.
3. Documentation: Detailed comments that describe the purpose, functionality, and usage of a piece of code, helping other developers understand the program's logic.
Real-world code examples:
#include <stdio.h>
// Function to calculate the factorial of a number
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
/* Main function that tests the factorial function */
int main() {
// Test the function with different numbers
int num1 = 5, num2 = 7;
printf("Factorial of %d is %d\n", num1, factorial(num1));
printf("Factorial of %d is %d\n", num2, factorial(num2));
return 0;
}
Step-by-step explanations:
1. The factorial()
function calculates the factorial of a number using a for loop.
2. In the main function, we test the factorial()
function with two numbers (5 and 7).
3. Comments are used to describe the purpose of the factorial()
function, the variables, and the functionality of the main program.
What causes it: Using an incorrect comment syntax, such as using multi-line comments within single-line comments or vice versa.
// /* This is bad code */
Error message:
example.c:1:10: error: expected expression before '/*' token
// /* This is bad code */
^
Solution: Correct the comment syntax to use either single-line or multi-line comments.
// This is a valid single-line comment
/* This is a valid multi-line comment */
Why it happens: The compiler encounters an unexpected token and cannot parse the code correctly.
How to prevent it: Use the correct syntax for single-line and multi-line comments.
What causes it: Failing to document a function or variable, making it difficult for other developers to understand the code's purpose and functionality.
int my_function(int arg1, int arg2); // Missing documentation
Solution: Add a detailed comment explaining the function's purpose, arguments, and return value.
/**
* @brief Calculates the sum of two integers
*
* @param arg1 The first integer to add
* @param arg2 The second integer to add
*
* @return The sum of arg1 and arg2
*/
int my_function(int arg1, int arg2);
Why it happens: Developers may overlook the importance of documentation or simply forget to include it.
How to prevent it: Establish coding standards that emphasize the need for documentation and use linters with custom rules to enforce these standards.