totn C Language

C Language: Comments

This C tutorial explains how to use comments in the C language with syntax and examples.

Description

In the C Programming Language, you can place comments in your source code that are not executed as part of the program.

Comments provide clarity to the C source code allowing others to better understand what the code was intended to accomplish and greatly helping in debugging the code. Comments are especially important in large projects containing hundreds or thousands of lines of source code or in projects in which many contributors are working on the source code.

A comment starts with a slash asterisk /* and ends with a asterisk slash */ and can be anywhere in your program. Comments can span several lines within your C program. Comments are typically added directly above the related C source code.

Adding source code comments to your C source code is a highly recommended practice. In general, it is always better to over comment C source code than to not add enough.

Syntax

The syntax for a comment is:

/* comment goes here */

OR

/*
 * comment goes here
 */

Note

  • It is important that you choose a style of commenting and use it consistently throughout your source code. Doing so makes the code more readable.

Example - Comment in Single Line

You can create an comment on a single line.

For example:

/* Author: TechOnTheNet.com */

C++ introduced a double slash comment prefix // as a way to comment single lines. The following is an example of this:

// Author: TechOnTheNet.com

This form of commenting may be used with most modern C compilers if they also understand the C++ language.

Example - Comment Spans Multiple Lines

You can create a comment that spans multiple lines. For example:

/*
 * Author: TechOnTheNet.com
 * Purpose: To show a comment that spans multiple lines.
 * Language:  C
 */

The compiler will assume that everything after the /* symbol is a comment until it reaches the */ symbol, even if it spans multiple lines within the C program.

Example - Comment at End of Code Line

You can create a comment that displays at the end of a line of code.

For example:

#define AGE 6    /* This constant is called AGE */

OR

#define AGE 6    // This constant is called AGE

In these examples, the compiler will define a constant called AGE that contains the value of 6. The comment is found at the end of the line of code after the constant has been defined.