Code: The Good and the Ugly

June 17, 2013

Jack Ganssle-June 17, 2013

Careful C craftsmanship creates correct code.

I'm just back from three weeks overseas. Despite daily trying to keep up with email, some just has to be done from the office; other items are less important and not worth dealing with from the road. So my e-mail inbox is stuffed to explosively-dangerous levels, the desk piled high with papers needed attention, and the voicemail is, well, happily minimal. E-comm has, for me at least, almost entirely replaced the phone over the last decade or so.

A couple of coding themes have popped up, though, from reading clients' code and e-mail from various correspondents.

First is an increasing trend I'm seeing where developers rely on an exquisite knowledge of precedence rules in C, usually inside of if statements. A generic example:

if( variable1 operator1 variable2 operator2 variable3)do_something;

Absent parenthesis to group elements of this expression, the result may be very surprising. The statement:

 if( variable1 & variable2 == variable3)do_something;

probably won't do what is expected. Ditto for:

 if( variable1 < variable2 < variable3)do_something;
I strongly believe in using parenthesis in any instance where there is the slightest possibility of confusion. Cost: zero. Benefit: possibly saving a lot of debugging and maintenance time.

(In fact, the code I read while traveling incorrectly combined operators and was the source of a long-lurking bug. That "exquisite knowledge precedence rules" was sorely lacking. There's a lot of complexity to the C standard, and it's a bad idea to assume one's own perfect understanding, or that of a colleague or future maintainer).

< Previous
Page 1 of 2
Next >

Loading comments...