Writing comments to clarify the program later
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 very often a good thing. However, there might be times where we need to step out of that consistency, and for some good reason, when we write code, that code becomes particularly twisted or obtuse and difficult to understand. Or, we might write code a certain way that might not be obvious or might not be expected, again for good reason. It is in these circumstances that we should comment on our code – not for the compiler, but for ourselves and others who might be reading our code later, often much later, scratching our/their foreheads and thinking, What? What did I/they intend to do here?
Code comments are a way to explain 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 in which comments in C can be employed.
Comments with tags (1)
–(6)
are old-style C comments. The rules for these are simple – when /*
is encountered, it is a comment until */
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 from tags (7)
to (10)
. When //
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.
Now that we know the various ways we can format comments, let's consider some effective ways for using them.
Some guidelines on commenting code
One of the best guidelines for commenting in code is the same guideline to follow in life. This is sometimes called the Goldilocks Principle, also known as the Three Bears Principle, named after the children's fairy tale, Goldilocks and the Three Bears. The essence of this guideline is not too much; not too little; just right. However, just right is subjective, it depends on several factors, and will be different for each situation. Your own judgment and experience must be your guide to your Goldilock's moment.
Here is a list of essential guidelines to follow when commenting on your code:
- Assume the reader already knows the language: You are not teaching your reader how to code. Do not explain the obvious features of the language. You are explaining the non-obvious aspects of your code.
- Write in full sentences with proper capitalization and punctuation: Comments are not code. They are the words you are writing to yourself or other readers of your code. Your comments will be much less cryptic and more easily understood if you follow this guideline.
- Comment on unusual uses of the language: Every language has oddities and idiosyncrasies that might not be used often or might be used in unexpected ways. These should be clarified and highlighted.
- Try to comment in a way that is resilient to code changes: Very often, as code changes, comments are not necessarily updated to match those changes. One way to mitigate this issue is to put comments in globs at the beginning of functions or to precede blocks of code rather than them being interspersed within code blocks. This is so that if those code blocks change, the comments are still valid. You will see examples of how to do this throughout this book.
- Comment at a high level: Describe the intent of the code and the way it attempts to solve a problem. This guideline goes hand in hand with the first guideline we mentioned. The higher the level the comments are describing, the less likely they will need to be changed as the code changes.
- Convey your intent: With your comments, strive to convey the intent of the code you are writing, why the code is needed, and what the code is trying to accomplish. What the code is actually doing should come from the code itself.
I am often surprised when I revisit a piece of code I wrote 6 months ago. Too often, I find that I am scratching my head asking why did I do this? or what was I thinking here? (both are cases of too little commenting). I also find that when I change code, I have to delete numerous comments that are no longer necessary (a case of too much commenting). I rarely find that I have commented too much when I have focused on the intent of the code (what was I trying to do here).
At one point in my career, I came across a programmer whose comments were completely divorced from the code that was there. I concluded that this programmer initially intended their algorithm to work one way, but then modified the code so significantly that the comments no longer matched the actual code at all. When I saw that programmer's name in subsequent code, after careful inspection, I simply deleted the code comments because I found them to be irrelevant. Please do not do this unless you are absolutely certain you understand the code and that the comments do not match the code.
Learning how to effectively comment on code is a lifelong challenge. I do not suppose you will learn this quickly. You will learn this after years of examining your code and making your code clearer to yourself, let alone making your code clearer to others. As we work through various C example programs, I intend to demonstrate a variety of useful and resilient commenting techniques.
Adding comments to the Hello, world! program
Now that we have explored the various ways we can comment on code and commenting styles, let's copy hello1.c
to hello2.c
and add appropriate comments.
You can either copy hello1.c
to hello2.c
with your command interpreter or, in your editor, open hello1.c
and immediately save it as hello2.c
. Regardless of how you do this, you should have both hello1.c
and hello2.c
in your Chapter1_HelloWorld
directory.
In your editor, modify hello2.c
so that it appears as follows:
/* * hello2.c * My first C program with comments. * by <your name> * created yyyy/mm/dd */ #include <stdio.h> int main() { printf( "Hello, world!\n" ); return 0; } /* eof */
Note how the *
character at the beginning of each line providing a comment makes it clear that there are several lines of comments in a group; the group begins with /*
and eventually ends with */
. Compile, run, and verify this program. Make sure you haven't introduced an accidental character here or there, which is always possible and should always be verified.
This is now a complete program. We know from the evidence from hello1.c
that the program is correct – it displays our intended message in the way we desire. The first six lines of comments provide minimal information about the program's author and the date it was written. This program's heading information can be simple or it can be more comprehensive. For now, we will keep such heading information simple.
The program itself is so simple that anyone who understands C would know that a simple message is printed. No further commenting is required here.
Finally, we mark the end of the file with a comment; the only benefit to such a marking is when there are multiple editor windows open and/or programs get very long. This simple demarcation lets us know we're at the EOF. This final EOF indicator is entirely optional and becomes more of a stylistic preference than a practice with rigorous rationale.
I have found that in every programming language I have used, my commenting style has adapted to the simplicity or obtuseness of the given language. When I programmed in assembler language at university or later in an early version of Fortran 4, I commented on almost every line. However, for C++ or Objective-C, I found I commented only sparsely or in globs – large sections of comments that explain a concept or programming solution.
Furthermore, even within a given language, when the problem being solved is unusual or I am using a novel approach to its solution, more comments are required.
In the remainder of this book, depending on the code sample, we'll explore various useful commenting practices that are effective, even when the code is subject to change.