C Comments

Summary: in this tutorial, you will learn about C comments and how to use them to document your code.

Introduction to the C comments

A comment is an annotation in the source code. Typically, you use a comment to make the code easier to understand. In C, a comment starts with a slash followed by an asterisk (/*) and ends with an asterisk followed by a slash (*/). For example:

#include <stdio.h> int main() { /* counter always starts at 0 */ int counter = 0; return 0; }
Code language: C++ (cpp)

In this example, the following line is a comment:

/* counter always starts at 0 */
Code language: C++ (cpp)

When the C compiler compiles the program, it ignores all the comments.

A comment can be on the same line with the code as follows:

#include <stdio.h> int main() { int counter = 0; /* counter always starts at 0 */ return 0; }
Code language: C++ (cpp)

When the comment is on the same line as the code, it is called an inline comment.

C allows a comment to span multiple lines as shown in the following example:

/* This is an example of a multi-line comment. */
Code language: C++ (cpp)

This is called a multi-line comment.

C99 inline comments

C99 allows you to write an inline comment that starts with two forward slashes (//). Everything after the two forward slashes belongs to the inline comment. For example:

#include <stdio.h> int main() { int counter = 0; // counter always starts at 0. return 0; }
Code language: C++ (cpp)

In this example, the text counter always starts at 0. is the inline comment.

Summary

  • Do use comments to add notes to your code to make it more clear.
  • A comment starts with a slash followed by an asterisk (/*) and ends with an asterisk followed by a slash (*/).
  • Use double slashes (//) to start an inline comment.
  • C compilers ignore the comments when compiling the code.
  • Do use clear and concise comments to document your code.
Was this tutorial helpful ?