The Ten Commandments for C Programmers (Annotated Edition)

Henry Spencer henry at zoo.toronto.edu
Sun Nov 4 13:16:18 AEST 1990


I've had a lot of favorable comments over time about my original Ten
Commandments for C Programmers, and the other day I was feeling whimsical
and decided it was time to add some detail...

#! /bin/sh
echo 'ten.ann':
sed 's/^X//' >'ten.ann' <<'!'
X.\" this document is formatted for the -ms macros, although it does not
X.\" rely on complex features thereof and should not be hard to translate
X.TL
XThe Ten Commandments for C Programmers (Annotated Edition)
X.AU
XHenry Spencer
X.IP 1
XThou shalt run \fIlint\fR frequently and study its pronouncements with
Xcare, for verily its perception and judgement oft exceed thine.
X.\" define some utility macros, now that we're safely out of the header stuff
X.de AS
X.in +1i
X.ll -1i
X.ps -2
X.vs -3
X.AP
X..
X.de AE
X.in -1i
X.ll +1i
X.ps +2
X.vs +3
X..
X.de AP
X.ne 4
X.sp 0.5
X..
X.AS
XThis is still wise counsel, although many modern compilers search out many
Xof the same sins, and there are often problems with \fIlint\fR
Xbeing aged and infirm, or unavailable in strange lands.
XThere are other tools, such as Saber\ C, useful to similar ends.
X.AP
X``Frequently'' means thou shouldst draw thy daily guidance from it,
Xrather than hoping thy code will achieve \fIlint\fR's blessing by a sudden
Xact of repentance at the last minute.
XDe-linting a program which has never been \fIlint\fRed before is often
Xa cleaning of the stables such as thou wouldst not wish on thy worst enemies.
XSome observe, also, that careful heed to the words of \fIlint\fR
Xcan be quite helpful in debugging.
X.AP
X``Study'' doth not mean mindless zeal to eradicate every byte of \fIlint\fR
Xoutput\(emif for no other reason, because thou just canst not shut
Xit up about some things\(embut that thou should know the cause of its
Xunhappiness and understand what worrisome sign it tries to speak of.
X.AE
X.IP 2
XThou shalt not follow the NULL pointer, for chaos and madness await thee at
Xits end.
X.AS
XClearly the holy scriptures were mis-transcribed here, as the words should
Xhave been ``null pointer'', to minimize confusion between the concept of
Xnull pointers and the macro NULL (of which more anon).
XOtherwise, the meaning is plain.
XA null pointer points to regions
Xfilled with dragons, demons, core dumps, and numberless other foul creatures,
Xall of which delight in frolicing in thy program if thou disturb their sleep.
XA null pointer doth \fInot\fR point to a 0 of any type,
Xdespite some blasphemous old code which impiously assumes this.
X.AE
X.IP 3
XThou shalt cast all function arguments to the expected type if they are not
Xof that type already, even when thou art convinced that this is unnecessary,
Xlest they take cruel vengeance upon thee when thou least expect it.
X.AS
XA programmer should understand the type structure of his language,
Xlest great misfortune befall him.
X.AP
XContrary to the heresies
Xespoused by some of the dwellers on the Western Shore,
X`int' and `long' are not the same type.
XThe moment of their equivalence in size and representation is short,
Xand the agony that awaits believers in their interchangeability
Xshall last forever and ever once 64-bit machines become common.
X.AP
XAlso, contrary to the beliefs common among
Xthe more backward inhabitants of the
XPolluted Eastern Marshes, `NULL' does not have a pointer type,
Xand must be cast to the correct type whenever it is used as a function
Xargument.
X.AP
X(The words of the prophet Ansi, which permit NULL to be defined as having
Xthe type `void\ *', are oft taken out of context and misunderstood.
XThe prophet was granting a special dispensation for use in cases of great
Xhardship in wild lands.
XVerily, a righteous program must make its
Xown way through the Thicket Of Types without lazily relying on this
Xrarely-available dispensation to solve all its problems.
XIn any event, the great deity Dmr who created C hath wisely endowed it
Xwith many types of pointers, not just one, and thus it
Xwould still be necessary to convert the prophet's NULL
Xto the desired type.)
X.AP
XIt may be thought that the radical new blessing of ``prototypes'' might
Xeliminate the need for caution about argument types.
XNot so, brethren.
XFirstly, when confronted with the twisted strangeness of variable numbers
Xof arguments, the problem returns... and he who has not kept his faith
Xstrong by repeated practice shall surely fall to this subtle trap.
XSecondly, the wise men have observed that reliance on prototypes doth
Xopen many doors to strange errors, and some indeed had hoped that prototypes
Xwould be decreed for purposes of error checking
Xbut would not cause implicit conversions.
XLastly, reliance on prototypes causeth great difficulty in the Real World
Xtoday, when many cling to the old ways and the old compilers out of desire
Xor necessity, and no man knoweth what machine his code may be asked
Xto run on tomorrow.
X.AE
X.IP 4
XIf thy header files fail to declare the return types of thy library functions,
Xthou shalt declare them thyself with the most meticulous care,
Xlest grievous harm befall thy program.
X.AS
XThe prophet Ansi, in her wisdom, hath added that thou shouldst also scourge
Xthy Suppliers, and demand on pain of excommunication that they
Xproduce header files that declare their library functions.
XFor truly, only they know the precise form of the incantation appropriate
Xto invoking their magic in the optimal way.
X.AP
XThe prophet hath also commented that it is unwise,
Xand leads one into the pits of damnation and subtle bugs,
Xto attempt to declare such functions thyself when thy header files do
Xthe job right.
X.AE
X.IP 5
XThou shalt check the array bounds of all strings (indeed, all arrays),
Xfor surely where thou typest ``foo'' someone someday shall type
X``supercalifragilisticexpialidocious''.
X.AS
XAs demonstrated by the deeds of the Great Worm,
Xa consequence of this commandment is that robust production software
Xshould never make use of \fIgets()\fR, for it is truly a tool of the Devil.
XThy interfaces should always inform thy servants of the bounds of thy arrays,
Xand servants who spurn such advice or quietly fail to follow it should
Xbe dispatched
Xforthwith to the Land Of Rm, where they can do no further harm to thee.
X.AE
X.IP 6
XIf a function be advertised to return an error code in the event of
Xdifficulties, thou shalt check for that code, yea, even though the checks
Xtriple the size of thy code and produce aches in thy typing fingers,
Xfor if thou thinkest ``it cannot happen to me'',
Xthe gods shall surely punish thee for thy arrogance.
X.AS
XAll true believers doth wish for a better error-handling mechanism,
Xfor explicit checks of return codes are tiresome in the extreme and
Xthe temptation to omit them is great.
XBut until the far-off day of deliverance cometh,
Xone must walk the long and winding road with patience and care,
Xfor thy Vendor, thy Machine, and thy Software delight in surprises
Xand think nothing of producing subtly meaningless results on the day before
Xthy Thesis Oral or thy Big Pitch To The Client.
X.AP
XOccasionally, as with the \fIferror()\fR feature of \fIstdio\fR, it is
Xpossible to defer error checking until the end when a cumulative result
Xcan be tested, and this often produceth code which is shorter and clearer.
XAlso, even the most zealous believer should exercise some judgement when
Xdealing with functions whose failure is totally uninteresting... but beware,
Xfor the cast to void is a two-edged sword that sheddeth thine own blood
Xwithout remorse.
X.AE
X.IP 7
XThou shalt study thy libraries and strive not to re-invent them without cause,
Xthat thy code may be short and readable and thy days pleasant and productive.
X.AS
XNumberless are the unwashed heathen who scorn their libraries on various
Xsilly and spurious grounds, such as blind worship of the Little Tin God
X(also known as ``Efficiency'').
XWhile it is true that some features of the C libraries were ill-advised,
Xby and large it is better and cheaper to use the works of others than to
Xpersist in re-inventing the square wheel.
XBut thou should take the greatest of care to understand what thy libraries
Xpromise, and what they do not, lest thou rely on facilities that may vanish
Xfrom under thy feet in future.
X.AE
X.IP 8
XThou shalt make thy program's purpose and structure
Xclear to thy fellow man by using the
XOne True Brace Style,
Xeven if thou likest it not,
Xfor thy creativity is better used in solving problems than in creating
Xbeautiful new impediments to understanding.
X.AS
XThese words, alas, have caused some uncertainty among the novices and
Xthe converts, who knoweth not the ancient wisdoms.
XThe One True Brace Style referred to is that demonstrated in the
Xwritings of the First Prophets, Kernighan and Ritchie.
XOften and again it is criticized by the ignorant as hard to use,
Xwhen in truth it is merely somewhat difficult to learn,
Xand thereafter is wonderfully clear and obvious,
Xif perhaps a bit sensitive to mistakes.
X.AP
XWhile thou might think that thine own ideas of brace style lead to clearer
Xprograms, thy successors will not thank thee for it,
Xbut rather shall revile thy works and curse thy name,
Xand word of this might get to thy next employer.
XMany customs in this life persist because they ease friction and promote
Xproductivity as a result of universal agreement,
Xand whether they are precisely the optimal choices is much less important.
XSo it is with brace style.
X.AP
XAs a lamentable side issue, there has been some unrest from
Xthe fanatics of the Pronoun Gestapo over the use of the word ``man''
Xin this Commandment,
Xfor they believe that great efforts and loud shouting devoted to the
Xritual purification of the language will somehow redound to the benefit
Xof the downtrodden
X(whose real and grievous woes tendeth to get lost amidst all that thunder
Xand fury).
XWhen preaching the gospel to the narrow of mind and short of temper,
Xthe word ``creature'' may be substituted as a suitable pseudoBiblical term
Xfree of the taint of Political Incorrectness.
X.AE
X.IP 9
XThy external identifiers shall be unique in the first six characters,
Xthough this harsh discipline be irksome and the years of its necessity
Xstretch before thee seemingly without end,
Xlest thou tear thy hair out and go mad on that fateful day when
Xthou desirest to make thy program run on an old system.
X.AS
XThough some hasty zealots
Xcry ``not so; the Millenium is come, and this saying is
Xobsolete and no longer need be supported'', verily there be many, many
Xancient systems in the world, and it is the decree of the dreaded god
XMurphy that thy next employment just might be on one.
XWhile thou sleepest, he plotteth against thee.
XAwake and take care.
X.AP
XIt is, note carefully, not necessary that thy identifiers be limited to a
X\fIlength\fR of six characters.
XThe only requirement that the holy words place upon thee is uniqueness
Xwithin the \fIfirst\fR six.
XThis often is not so hard as the belittlers claimeth.
X.AE
X.IP 10
XThou shalt foreswear, renounce, and abjure the vile heresy which claimeth
Xthat ``All the world's a VAX'', and have no commerce with the
Xbenighted heathens who cling to this barbarous belief,
Xthat the days of thy program may be long even though the days of thy
Xcurrent machine be short.
X.AS
XThis particular heresy bids fair to be replaced by ``All the world's a Sun''
Xor ``All the world's a 386'' (this latter being a particularly revolting
Xinvention of Satan), but the words apply to all such without limitation.
XBeware, in particular, of the subtle and terrible ``All the world's a
X32-bit machine'', which is almost true today but shall cease to be so
Xbefore thy resume grows too much longer.
X.AE
!
echo done
-- 
"I don't *want* to be normal!"         | Henry Spencer at U of Toronto Zoology
"Not to worry."                        |  henry at zoo.toronto.edu   utzoo!henry



More information about the Comp.lang.c mailing list