Friday, February 23, 2007

Use the braces, stupid!

Upon further reading of Programming in C (3rd ed.) by Stephen G. Kochan, I have a discovered a flaw in this otherwise excellent book: the author doesn't always use braces around the bodies of if/else statements and loops. On the whole, I can live with this defect. However, as someone who has done research on the causes of bugs in software, I can confidently say that omitting braces causes bugs. For example:
for (j = 0; j < m; ++j)
for (i = 0; i < n; ++j)
f();
g();
The call to g() is not in the body of either loop. This may seen contrived, but FindBugs found several examples of similar bugs in a Java library that shall remain nameless.

A bug in released software can easily cost thousands or tens of thousands of dollars to fix; using braces consistently eliminates a common cause of defects.

No comments: