A lot about writing good code is writing code in a consistent manner. Consistency makes it somewhat easier for the reader (or you) to comprehend at a later time. Consistency is most often a good thing. However, there may be times where we need to step out of that consistency, and for some goodreason, when we write code, that code is particularly twisted or obtuse and difficult to understand. Or, we might write code a certain way that may not be obvious or may not be expected, again for good reason. It is in these circumstances we should comment on our code – not for the compiler, but for ourselves and for others who may be reading our code at a later date, scratching our/their foreheads thinking, "What? What did I/they intend to do here?"
Code comments are the way to provide an explanation of why a particular piece of code is written in a certain way. Let's explore some of the different ways we can write code comments in C.
Comments in code, when done correctly, are ignored by the compiler. They are only for human edification. Consider the following code comments:
/* (1) A single-line C-style comment. */
/* (2) A multi-line
C-style comment. */
/*
* (3) A very common way to
* format a multi-line
* C-Style comment.
*/
/* (4) C-style comments can appear almost anywhere. */
/*(5)*/ printf( /* Say hello. */ "Hello, world!\n" );
/*(6)*/ printf( "Hello, world!\n" ); /* Yay! */
// (7) A C++ style comment (terminated by End-of-Line).
printf( "Hello, world!\n" ); // (8) Say hello; yay!
//
// (9) A more common way
// of commenting with multi-line
// C++ style comments
//
// (10) anything can appear after //, even /* ... */ and
// even more // after the first // but they will be
// ignored because they are all in the comment.
The comments illustrated in the preceding code are not particularly useful comments, but they show various ways comments in C can be employed.
Comments with tags (1)–(6) are old-style C comments. The rules for these are simple – when a /* is encountered, it is a comment until a */ is subsequently encountered, whether it appears on the same line or several lines later. / * (with a space between them) and * / (with a space between them) are not valid comment indicators.
C comments that have been adopted from C++ are shown with tags (7) through (10). When a // is encountered, it is a comment until an End Of Line (EOL) is encountered. Therefore, these comments cannot appear anywhere like C comments can. Likewise, / / (with a space between them) is not a valid comment indicator.
C comments are more flexible, while C++ style comments are more obvious. Both styles are useful. We'll use both throughout this book.