Comments on Comments

In-line comments should be outlawed.

You know the ones, like this:

a=out_pr * scale; // scale the input

where the comment is appended to a line of C or C++ code.

Code infested with this commenting strategy invariably, especiallyafter long in maintenance, looks like a bar-hopper weaving his drunkenway down the street. Like this:

scale_ad(base_val);// set A/D ref
base_val=offset/2; // adjust bypower of two
hypotenuse=sqrt(side_a*side_a+side_b*side_b);// find side

Comments are supposed to be distinct from the code. Though part ofthe program, they present the information in a different sort ofcontext, and may be read independently of the code. But, as thisexample shows, your eyes struggle to find where the C ends and thecomments begin.

Usually we start a project determined to write pretty code, andcraft a rule to start all comments in a particular column. That linesthings up beautifully, but greatly increases the hassle of maintenance.Change just a single character and you've got to realign the startingpair of slashes. Why force developers to work so hard? Especially whenwe know, under deadline pressure, we won't?

This artificial demarcation means it's hard to fit a statement inthe allotted space before the “//” .Sure, it's possible to continue a Cstatement over multiple lines, but breaking up a statement in acomprehensible way, especially when using long variable names, can behard.

With comments appended to the C lines there's an essential tensionbetween keeping the C short so as to not run into the double slashes,and picking a starting line number not so high that all of the commentsstart in a column waaaay out to the right, pushed off the screen of areasonably-sized editor window.

The decision to start a line of documentation on, say, line 60limits the length of the comment. We remove words, context and meaningto fit the comment into the 20 or 40 characters left before the end ofthe editor window. What should be “disable all safety warnings” getscompressed to “dis warns,” leaving some future maintainer to wonder whywe'd want to dis anyone, let alone a warning.

I prefer using comment blocks, which are large enough to permit acomplete description. So,

/*Adjust the input by “scale”, which
is the coefficient calculated at
calibration time.

is far better than

a=out_pr * scale; // scale the input

(In assembly, where each instruction does so little and themnemonics are short, in-line comments are fine).

Obviously, this is my opinion. Yours may differ. What is your Ccommenting strategy?

Jack G. Ganssle is a lecturer and consultant on embeddeddevelopment issues. He conducts seminars on embedded systems and helpscompanies with their embedded challenges. Contact him at . His website is .

Reader Response

Also… When inline comments are tabbed, the code can be cumbersome to read. The engineer's eyes are forced to dart from the code on the left hand side of the screen over to finding the aligned comment on the right hand side.

It is more intuitive and natural to read the comment drop down a line, and then read the relating code. White space costs nothing!

–Peter Hall
Crowborough, UK

I share your views, mostly. I find that several commenting styles make sense depending on the context.

I use the comment block approach when it makes sense to describe a function in detail. However, I seldom use the /* */ delimiters for a block as I've been burned when a trailing delimiter was inadvertently deleted or modified. It wasn't clear that entire sections of code weren't compiling — or why — until after some serious head scratching. With today's syntax highlighting editors and IDE's, this is no longer a problem. Nonetheless, // rules the day for comment blocks.

I also use inline comments when the comment can afford to be short and it adds some guidance to the big block comment at the beginning of a function. I try to start my inline comments all in the same column but as you pointed out, this is difficult to achieve consistently. However, my comments don't wander all that much. They may start out in column 53 for one function, then wander over to 57 for the next function. So for many pages of code and for a complete function the comments do line up. Additionally I find that modern editors allow much longer lines of text than were available in the 80 column monitor days of old. Keeping inline comments short and thereby lacking meaning I think is no longer a constraint. My editor allows between 115 and 140 characters on the screen at once (and yes, I can actually read them) although I never take advantage of these long lines. I never go past column 100.

So I say, use // religiously and intermix comment blocks and inline comments “as appropriate”. Oh, I also have function descriptor blocks ahead of EVERY function. These serve to document entry/ exit parameters as well as function and algorithm. If function headers are done thoroughly, inline comments almost become unneccessary.

–Stephen Ciricillo
Liverpool, NY

I occasionaly use a comment at the end of line of C++ code, but only if it only relates to the current line of code and only if commenting it makes sense at all.

The observation “your eyes struggle to find where the C ends and the comments begin” is only valid if you use an editor without syntax highlighting and I don't think that this percentage of programmers is high. I mean: who is still using Notepad for entering C/C++ code? In my editors (Rose realtime and pspad) comments show up in green so you can easily make a distinction between code and comments.

–Ton Janssen
Venlo, Netherlands

Oh well, here we go again — coding style, and this time around we are commenting on comments.

Appending comments to the end of line does not really make anything hard to read as long as we are using an editor capable of context high-lighting in a color window instead of vi on a VT100.

I still get to satisfy my nostalgia by using vi for some emergency editing on a remote system with limited access, but this is not where I normally do code review. And, since it is usually an emergency, there is not much time to complain but to fix the configuration quickly and get out.

IMHO, a lot more damage is done by lines that start at column 48 and run through column 105 as a result of poorly planned nesting.

–David Liu
VIMA Technologies Inc.
Santa Barbara, CA

Four-score and …. heh!Who reads comments anyway? Usually, I have found that almost no one does. Really! Sometimes, to test this, I embed something funny, or a joke or two. Then I mention this, and no one even notices!

So, in practice, I have found the following things:- comments are mostly used by the original developer- some folks write very little or none at all- RTFC seems to be the nom-deguerre these days; especially in the Linux world!

RTFC == R ead T he F rikkin C ode!

–Ken Wada
Sr Embedded Systems Consultant
Aurium Technologies Inc
San Jose, CA

Using comments at the end of a line is generally not a good idea. Distinguishing comments is not a problem if you're using a syntax highlighter, but what if you're using a visual “diff” tool? Many code reviewers use such a tool to determine and evaluation changes…and syntax highlighting is not available in many of these (if not all). Also, what if the code is printed? I suspect the 80 character per line “rule” may not be dead yet.

–Jim Esterby
Lititz, PA

/*     Title: Name the block of code    Who: Author    Description: What it does*/   

–Steve King
Raytheon RMS
Tucson, AZ

Colour syntax highlighting suggested by others may make the code readable on-screen. But I often like to print my code, so I can move away from the computer and scribble notes it. Paper beats a screen for seeing the bigger picture when restructuring code. Sure I might print it in colour, but that can get expensive for something that is quickly going to end up in the recycle bin.

– Clifford Slocombe

I avoid inline comments totally. The reason being that readability of the code is lost.

I prefer to have a commenting style like

* My comments are here
* This is the second line of comment

This in my view ensures better readability.

– Sethuraman G.

I fell like such an outcast! I started my programming in assembly, so I've always commented my code with the descriptive text on the right.

/* */ comments should only be used to remove large chunks of code. A good alternative is #if (0) #endif to remove the block for testing purposes. You can't nest /* */, but you can next // within /* */.

// comments should be used for describing (commenting) to code, or to remove single lines during maintenance.

Like David Liu said, too much indentation (4 per tab, please) is worse. I start all line-oriented comments in column 57, and it is indented appropriate to the text.

I utterly disdain a block of comments above the code they describe, unless used as a descriptive header for a function. And then, each line should begin with //. Just like the old semi-colon used to do for us.

I can't be doing too badly using this style. My boss (an analog EE) can read my code and understand exactly what I'm doing. Not only that, but I can come back to the same code years later and still understand it!

– Andy Kunz

1st rule: ANY commenting of code is better than no commenting at all! (why is so much open-source not commented??)

2nd rule: // with a quick note is SO MUCH FASTER than a comment block. Emphasis: Making rule #1 easier to comply with!

I'm willing to bet we all use a combination of blocks & inline. Any method – pretty or not! – that adds *knowledge* to the code is GOOD.

Frankly, NOBODY (including me) comments enough – ever try to understand that code you wrote 3 years ago?

Bottom line: *Any* method that helps comments to go in is fine by me.

– Jim Ostrosky

I agree that end-of line comments are generally a bad idea, except in the case of #define's for register values, “packed” data structures, and other similar situations:

#define REG_ADDRESS 0x4000 // register address
#define REG_ENABLE_TX 0x01 // enable transmit section
#define REG_ENABLE_RX 0x02 // ” receive section
#define REG_ENABLE_HFC 0x04 // ” hardware flow control

typedef struct
UINT8 len; // packet length (total)
UINT8 id; // ” identifier
UINT32 crc; // ” CRC
UINT8 data[100]; // ” data payload

– Harry Jones

I agree completely with Jim Ostrosky. Any commenting is better than none. We specialize in testing other peoples code and have seen every combination imaginable, including essentially uncommented code.

– Scott Nowell

Come on Jack, admit it; you couldn't think of anything to talk about this week so you're stirring the pot with this topic!

Well it worked!

1. If you're gonna get hung up on commenting style, you've got way too much time on your hands.

2. I like the RTFC comment, but all too often you RTFC, and can understand WHAT it's doing, but still can't understand WHY you're doing it! Comments help the poor devil who has to maintain this code (which may yourself years later..) what the frik you were originally trying to do!

3. Like any writing (code included), comments should be succinct, but as descriptive as possible. When they're ambiguous, they help no one.

4. Like the code, comments need to be maintained. So much code is ported to new applications with the original comments left intact, it's enough to drive a programmer crazy!

I have actually received formal training in writing C code (years ago..) and our instructors emphasized not only good programming practices, but copious documenting (commenting) standards as well. Anyone (almost) can write code that works; it's quite another thing to be able to write code that can easily be maintained!

– greg w

I agree with Jack on this one. One exception in when commenting a structure definition– I use a block header to describe why the structure is needed, and aligned in-line comments after each element in the structure that provides additional information about each field.

When using block comments, I like to use the format:

/* Some comments
** More comments

This is because I am forced (on some projects) to not use the “//” commenting prefix, which I prefer if it is available.

Comments should not contain information that can be gleaned by reading the source code– in other words the comment should be about WHY the code is needed, and should convey the intention of the writer. Simply parroting the name of the function in a header block is bad form, and then it becomes an additional thing that must be maintained if the function name changes.

People that write code without commenting about their intentions should be ashamed of themselves– it is just plain unprofessional. “RTFC” is for high-school hackers, not software engineers.

– Ken Peek

There's two places I do use the in-line comments. Otherwise, it's kind of silly I agree.

switch ( ) {
case 1: // HERE
case 2: // HERE

and to describe a dangling else, eg,

if ( x ) {
} else if ( y ) {
} else { // if ( z )

– Matthew Staben

Any code needs comments. Inline comments are better than no comments. In fact, inline comments are better than a general comment at the beginning of a function.

I have had to deal with too many “software experts” who hack out code with insufficient comments.

If the comments are not sufficient, the job is not done. C code can be even more convoluted than Assembly code. Doing things “cute” does not fly unless you are under a memory crunch. But then, you still have to comment the stuff.

I refuse to accept code as being done from my team or other consultants UNLESS there are sufficient comments.

Non commented code is a sign of either incompetence or arrogance, neither should be tolerated.

– Keith Mullins

I guess it all comes down again to what is said on the comment.

I personally find this improper:

a= out_pr * scale; // scale the input

(other than the fact that the comment says pretty much the same as the code)

I'd rather have it like:

// scale the input
a= out_pr * scale;

But I think a comment at the end of the line should be valid if trying to explain a specific reason why something was done the was it was.

Examples: “The cast is necesary due to bug in compiler”, “variable 'scale' is in pseudo-fractional format 1.15”

– Rodrigo Flores

My slant on commenting seems a little different than most here. I want comments to answer the question “why” not the question “what”. I read and maintain comments scrupulously. I have to cope with a lot of code written years ago by a coffee-crazed programmer who cannot be trusted, most probably myself. If knowing what the code does were sufficient, RTFC (“Reading The Code”) would be also. But RTFC tells me nothing about whether the code serves its intended purpose, what that intent is or was, or if there are restrictions on when and how the code should be used. This relates closely to the concept of “design by contract” that was covered in previous JG columns. Lacking the luxury of a tool that can validate formalized contract assertions, at a bare minimum I want a clear and accurate statement of purpose, for the body of code as a whole, and if it has a complex structure, the major sections within. Then let the code that follows clearly reflect the purpose. On rare occasions, I will use the tagged comment style for one critical line of code to explain WHY that one line is the way it is, for example, to enforce a timing constraint that has no explicit representation in the coding.

– Larry Trammell

I agree with the commenters who say no one comments enough.

The people who say “comments are useless and misleading!” have never maintained code for a living. And yes, most open-source code is woefully badly or un-commented – and it hurts open source, especially since you have people NOT familiar with the code or with the assumptions the code is written under trying to modify it.

Here's something I wrote a while back on Slashdot: (

I see comments EXACTLY like this:
i=i+1; /* Add one to i */

Then find some better programmers to work with, or teach them how the write more useful comments.

That style makes sense in one, and only one usage: ASM code. Even there, it should be used with care. (Ok, and in APL).

comments can lie

I worked with a programmer who disliked comments so much he'd remove them before looking at a function. Ok. So I wrote some code and he came to me and said “why do you have an empty else case?” I was puzzled, then realized that I'd written something like this:

/* we don't have to do anything in the else case because of x y and z */

where x y and z would be non-obvious to anyone who wasn't fully immersed in this code. He's run it through a filter that removed all comments. He was a genius programmer – but wrote code that almost no one else could ever maintain. Tons of reliances on edge conditions without comment, reuse of generically-named variables (1 and 2 character names), tricky (but efficient) algorithms. So far as I know, I was the only one there ever to manage to really grok his code, and that required days of immersing myself.

x = x++; // add one to x

is obviously not useful.

// Test FU_E (End bit) after FU_A/FU_B test! If there's a gap, do not consider
// hitting the End bit a marker to stop – continue until we see another
// packet/timestamp (in which case we return TRUE), or until we are
// at the end of the buffer (in which case we return FALSE and keep
// hoping to assemble it).
if (((*curr)->GetPayload()[1] & FU_E_BIT) && !gap)
break; // no error in fragment
// if there's a gap we still won't return true unless
// we find a non-fragment packet (or one from another fragment!)

This is an example of a useful comment – and yes, it has to be maintained if the line of source were to change. I chose that at random; there are better examples – such as explaining what the edge cases are (especially if not handled), and under what circumstances they would become relevant, and how they could be dealt with then.

– Randell Jesup

One other thing: In this day and age why does someone have a mandate that comments begin in column N?? And warp the code to fit the commenting style???? That's a throwback to hard-core assembly-language coding style, sounds like.

– Randell Jesup

In my experiance most end of line comments are an attempt to better explain what the variables are being used for. This impulse on the part of the programmer indicates to me that the real problem is variable names that aren't very meaningful.

If you feel you need to add a 4 or 5 word comment to make a line of code more understandable, then try renaming the variables using those same words. This often makes the end of line (or preceeding line) comment redundant. More meaningful variable names makes all of your code more comprehendable, not just that one line of code. Plus it makes it easier to notice when you are using variables incorrectly.

Which line of code needs a comment and which one would you rather read?

Travel = TempCnt * Factor; //Belt Travel = Pulse Count * Pulses Per Meter Factor .

BeltTravel = PulseCount * PulsesPerMeter;

– Philip Ouellette

Its always better to write comment on new line, instead of adjacent to C code line

For example,

#define MAX_VALUE 500 /*max voltage*/

and in some peice of code it may be compared to take some decesion say,

if(MAX_VALUE == *ADCreg)

We dont have idea about the compiler which is used to compile the code so it may possible that during compilation time the macro MAX_VALUE is replaced by “500 /*max voltage*/” instaed of actual value “500” Therefore, it always better to put comments on new line.

– Satish Sharma

1 thought on “Comments on Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.