Skip to main content

Code Comments in C Programming

What is a code comment

A code comment is a piece of text in a computer program that is not executed as part of the program.

  • Comments are added to code to provide additional context or explanations of what the code is doing.
  • They are often used to explain the reasoning behind a particular piece of code, or to provide documentation for other developers who may be working on the same codebase.
  • There are two types of comments in C - single-line comments and multi-line comments.

Single-line comments

Single-line comments in C start with the // symbol and continue until the end of the line. Anything on the same line after the // symbol is treated as a comment and is not executed as part of the program.

Here is an example of a single-line comment in C:

#include <stdio.h>

int main(int argc, char** argv) {
// This is a single-line comment

printf("Hello, world!\n");

return 0;
}

Exmplanation

In the example above, the line // This is a single-line comment is a single-line comment. It is ignored by the compiler and is not executed as part of the program.

Multi-line comments

Multi-line comments in C start with the /* symbol and continue until the */ symbol. Anything between these symbols is treated as a comment and is not executed as part of the program.

Here is an example of a multi-line comment in C:

#include <stdio.h>

int main(int argc, char** argv) {
/*
* This is a multi-line comment.
* It can span multiple lines.
*/

printf("Hello, world!\n");

return 0;
}

Exmplanation

In the example above, the comment /* This is a multi-line comment. It can span multiple lines. */ is a multi-line comment. It spans multiple lines and is ignored by the compiler.

Best practices for using comments

  • To explain the reasoning behind a piece of code: why a particular piece of code was implemented in a certain way.

  • To provide context: such as explaining how it fits into the overall structure of the program.

  • Keep comments up to date: If you make changes to the code, be sure to update any related comments to reflect those changes. Outdated comments can be confusing for other developers who may be working on the same codebase.

  • Use clear and concise language: Keep your comments brief and to the point to make it easier for other developers to understand the code.

  • When writing a function: use comments to document its interface, including the purpose of the function, its input parameters, and its return value.

  • Avoid overusing comments: Too many comments can make the code harder to read and understand.