4.4. A Word about Style¶
Consistency leads to better programs. [1] If the same construct
(for
loop, while
loop, … ) is done exactly the same
way every time, then any variation suggests a genuine difference that is
worth noting.
Like natural languages, programming languages have idioms –
conventional ways that experienced programmers write common pieces
of code. A central part of learning any language is developing a
familiarity with its idioms. When things are expressed using phrases or code
that do not fit with the idiomatic mores of the language, the result is
often confusion. For example, one might write a for
loop as
follows.
for( i = 0; i <= (n - 1); ) array[i++] = 1;
Or like:
for( i = n-1; i >= 0; i--) array[i] = 1;
Both of these are correct, but the idiomatic form is like this:
for( i = 0; i < n; i++) array[i] = 1;
Footnotes
[1] | For more information see Section 1.3 of The Practice of Programming by Brian Kernighan and Rob Pike. |