comments
In C programming, comments are used to provide explanations or annotations in the source code. Comments make the code more understandable for developers who may work on the codebase later. The C language supports two types of comments:
Single-line comments: These comments start with // and continue to the end of the line. Anything written after // on the same line is considered a comment and is ignored by the compiler.
// This is a single-line comment.
int main() {
// This is also a single-line comment.
return 0; // Comment after code.
}
Multi-line comments: These comments start with /* and end with */. Anything between these delimiters is a comment and will be ignored by the compiler.
/*
This is a multi-line comment.
It spans several lines.
*/
int main() {
/* This is also a multi-line comment,
but it's on multiple lines to fit beside code. */
return 0;
}
Important Notes:
Nested multi-line comments are not supported. That is, you cannot start a new multi-line comment before closing the previous one.
/* This is the start of the first comment
/* This is incorrect and will cause a compilation error */
This is still part of the first comment */
Comments do not affect the behavior of the program; they are only for human readers.
Be careful when commenting out code. Using multi-line comments around code that already contains multi-line comments can lead to compilation errors.
Best Practices:
- Use comments to explain why certain code exists, not what it does (unless it's particularly complex).
- Keep comments up-to-date when modifying the code; outdated comments can be misleading.
- Avoid commenting out large sections of code; use version control systems for that.
- Use consistent commenting style throughout the codebase.