The Importance of Comments in C Programming: Best Practices

Comments in C

When it comes to documenting your C applications, you should utilize comments liberally in the source code. In C, comments can be inserted in two different ways: line comments start with // and end with the next new line character, while block comments start with /* and end with */.

The /* and */ delimiters can be used to encapsulate comments spanning multiple lines as well as to start and end comments inside a line. The ellipsis (…), for instance, in the function prototype below indicates that the open() method takes a third optional parameter. The following note clarifies how to use the optional parameter:

int open( const char *name, int mode, ... /* int permissions */ );

When writing source code, you can write it in two columns, with program code on the left and comments on the right, by using the notation // to insert comments that take up a whole line:

const double pi = 3.1415926536; // Pi is constant 

The majority of compilers supported these line comments even before the C99 standard formally introduced them to the C language. Despite coming from BCPL, C’s predecessor, these comments are occasionally referred to as “C++-style” comments.

The characters /* and // do not begin a comment inside the quotation marks that delimit a character constant or a string literal. For instance, there are no remarks in the statement that follows:

printf( "Comments in C begin with /* or //.\n" ); 

It is not possible to stack block comments since the preprocessor only searches for the comment’s end when analyzing the characters in a comment. Nevertheless, you can comment out a portion of a program that has line comments by inserting /* and */:

Two lines have been temporarily removed: const double pi = 3.1415926536; // Pi is constant; area = pi * r * r; // Determine the area that has been temporarily deleted up to this point */.

A conditional preprocessor command (explained in Chapter 14) can be used to comment out a portion of a program that has block comments in it:

/* Temporarily removing two lines:
const double pi = 3.1415926536; // Pi is constant
area = pi * r * r // Calculate the area
Temporarily removed up to here */

Every comment is changed by the preprocessor to a space. Thus, the two tokens, min Value, are formed from the character sequence min/*max*/Value.

Naveed Tawargeri

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.