[comp.lang.c] The Ten Commandments for C Programmers

henry@utzoo.uucp (Henry Spencer) (04/27/89)

Enough people have asked about these, after I alluded to them, that I
think it's reasonable to re-post them:

--------------
.TL
The Ten Commandments for C Programmers
.AU
Henry Spencer
.IP 1
Thou shalt run \fIlint\fR frequently and study its pronouncements with
care, for verily its perception and judgement oft exceed thine.
.IP 2
Thou shalt not follow the NULL pointer, for chaos and madness await thee at
its end.
.IP 3
Thou shalt cast all function arguments to the expected type if they are not
of that type already, even when thou art convinced that this is unnecessary,
lest they take cruel vengeance upon thee when thou least expect it.
.IP 4
If thy header files fail to declare the return types of thy library functions,
thou shalt declare them thyself with the most meticulous care,
lest grievous harm befall thy program.
.IP 5
Thou shalt check the array bounds of all strings (indeed, all arrays),
for surely where thou typest ``foo'' someone someday shall type
``supercalifragilisticexpialidocious''.
.IP 6
If a function be advertised to return an error code in the event of
difficulties, thou shalt check for that code, yea, even though the checks
triple the size of thy code and produce aches in thy typing fingers,
for if thou thinkest ``it cannot happen to me'',
the gods shall surely punish thee for thy arrogance.
.IP 7
Thou shalt study thy libraries and strive not to re-invent them without cause,
that thy code may be short and readable and thy days pleasant and productive.
.IP 8
Thou shalt make thy program's purpose and structure
clear to thy fellow man by using the
One True Brace Style,
even if thou likest it not,
for thy creativity is better used in solving problems than in creating
beautiful new impediments to understanding.
.IP 9
Thy external identifiers shall be unique in the first six characters,
though this harsh discipline be irksome and the years of its necessity
stretch before thee seemingly without end,
lest thou tear thy hair out and go mad on that fateful day when
thou desirest to make thy program run on an old system.
.IP 10
Thou shalt foreswear, renounce, and abjure the vile heresy which claimeth
that ``All the world's a VAX'', and have no commerce with the
benighted heathens who cling to this barbarous belief,
that the days of thy program may be long even though the days of thy
current machine be short.
--------------
-- 
Mars in 1980s:  USSR, 2 tries, |     Henry Spencer at U of Toronto Zoology
2 failures; USA, 0 tries.      | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

pjh@mccc.UUCP (Pete Holsberg) (04/29/89)

In article <1989Apr26.191350.7151@utzoo.uucp> henry@utzoo.uucp (Henry Spencer) writes:

=Thou shalt make thy program's purpose and structure
=clear to thy fellow man by using the
                     ^^^
                     
Say, Henry, you won't mind if I change that to "programmers" or
"computeroids" or "computersaurus" or something before I hand it out to
my classes???  ;-)

Pete
-- 
Pete Holsberg                   UUCP: {...!rutgers!}princeton!mccc!pjh
Mercer College				CompuServe: 70240,334
1200 Old Trenton Road           GEnie: PJHOLSBERG
Trenton, NJ 08690               Voice: 1-609-586-4800

henry@utzoo.uucp (Henry Spencer) (04/30/89)

In article <693@mccc.UUCP> pjh@mccc.UUCP (Pete Holsberg) writes:
>=Thou shalt make thy program's purpose and structure
>=clear to thy fellow man by using the
>                     ^^^
>                     
>Say, Henry, you won't mind if I change that to "programmers" or
>"computeroids" or "computersaurus" or something before I hand it out to
>my classes???  ;-)

Standard pseudoBiblical usage :-) follows the English-language convention
that masculine forms double as generic forms, even though use of this
slightly unfortunate convention is now believed to be the moral equivalent
of rape or child abuse (to judge by the reactions the most innocent remarks
can produce).

However, if you (un-bravely but also understandably) want to avoid attracting
the attention of the Pronoun Gestapo, it is permissible to substitute a 
suitably Biblical term like "creature" for "man".
-- 
Mars in 1980s:  USSR, 2 tries, |     Henry Spencer at U of Toronto Zoology
2 failures; USA, 0 tries.      | uunet!attcan!utzoo!henry henry@zoo.toronto.edu

mat@mole-end.UUCP (Mark A Terribile) (05/01/89)

> =Thou shalt make thy program's purpose and structure
> =clear to thy fellow man by using the
                      ^^^
                      
> Say, Henry, you won't mind if I change that to "programmers" or
> "computeroids" or "computersaurus" or something before I hand it out to
> my classes???  ;-)

Speaking as a bystander, please don't.  Change it to

   Thou shalt make thy program's purpose and structure
   clear to thy fellows by using the
                      ^
Let's not butcher artistic butchery of the language!

					Oh, the code has subtle bugs dear,
					And they surface soon or late.
					Just an sdb has the Guru
					But his skill is very great ...
-- 

(This man's opinions are his own.)
From mole-end				Mark Terribile

pjh@mccc.UUCP (Pete Holsberg) (05/02/89)

In article <1989Apr30.003346.25362@utzoo.uucp> henry@utzoo.uucp (Henry Spencer) writes:
=In article <693@mccc.UUCP> pjh@mccc.UUCP (Pete Holsberg) writes:
=>=Thou shalt make thy program's purpose and structure
=>=clear to thy fellow man by using the
=>                     ^^^
=>                     
=>Say, Henry, you won't mind if I change that to "programmers" or
=>"computeroids" or "computersaurus" or something before I hand it out to
=>my classes???  ;-)
=
=Standard pseudoBiblical usage :-) follows the English-language convention
=that masculine forms double as generic forms, even though use of this
=slightly unfortunate convention is now believed to be the moral equivalent
=of rape or child abuse (to judge by the reactions the most innocent remarks
=can produce).
=
=However, if you (un-bravely but also understandably) want to avoid attracting
=the attention of the Pronoun Gestapo, it is permissible to substitute a 
=suitably Biblical term like "creature" for "man".

The creatures in my class will *love* that!  Thanks.
-- 
Pete Holsberg                   UUCP: {...!rutgers!}princeton!mccc!pjh
Mercer College				CompuServe: 70240,334
1200 Old Trenton Road           GEnie: PJHOLSBERG
Trenton, NJ 08690               Voice: 1-609-586-4800

pjh@mccc.UUCP (Pete Holsberg) (05/04/89)

In article <159@mole-end.UUCP> mat@mole-end.UUCP (Mark A Terribile) writes:
=> =Thou shalt make thy program's purpose and structure
=> =clear to thy fellow man by using the
=                      ^^^
=                      
=> Say, Henry, you won't mind if I change that to "programmers" or
=> "computeroids" or "computersaurus" or something before I hand it out to
=> my classes???  ;-)
=
=Speaking as a bystander, please don't.  Change it to
=
=   Thou shalt make thy program's purpose and structure
=   clear to thy fellows by using the
=                      ^
=Let's not butcher artistic butchery of the language!

Mark, that was a joke.  You have a Terribile sense of humor!


-- 
Pete Holsberg                   UUCP: {...!rutgers!}princeton!mccc!pjh
Mercer College				CompuServe: 70240,334
1200 Old Trenton Road           GEnie: PJHOLSBERG
Trenton, NJ 08690               Voice: 1-609-586-4800

henry@zoo.toronto.edu (Henry Spencer) (11/04/90)

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@zoo.toronto.edu   utzoo!henry

tom@ssd.csd.harris.com (Tom Horsley) (11/05/90)

>>>>> Regarding The Ten Commandments for C Programmers (Annotated Edition); henry@zoo.toronto.edu (Henry Spencer) adds:

henry> Thy external identifiers shall be unique in the first six characters,
henry> though this harsh discipline be irksome and the years of its
henry> necessity stretch before thee seemingly without end, lest thou tear
henry> thy hair out and go mad on that fateful day when thou desirest to
henry> make thy program run on an old system.

henry> Though some hasty zealots cry ``not so; the Millenium is come, and
henry> this saying is obsolete and no longer need be supported'', verily
henry> there be many, many ancient systems in the world, and it is the
henry> decree of the dreaded god Murphy that thy next employment just might
henry> be on one.  While thou sleepest, he plotteth against thee.  Awake and
henry> take care.

Not true. I have freedom of choice. I can refuse to work on systems so brain
dead they only support 6 character externals, and I urge all other
programmers to make the same choice.

Boycott stupid linkers! Death to the wielders of stone knives and bearskins!
Computers should be useful tools, not millstones around the necks of
programmers.
--
======================================================================
domain: tahorsley@csd.harris.com       USMail: Tom Horsley
  uucp: ...!uunet!hcx1!tahorsley               511 Kingbird Circle
                                               Delray Beach, FL  33444
+==== Censorship is the only form of Obscenity ======================+
|     (Wait, I forgot government tobacco subsidies...)               |
+====================================================================+

mjd@saul.cis.upenn.edu (Mark-Jason Dominus) (11/06/90)

In article <TOM.90Nov5072220@hcx2.ssd.csd.harris.com> tom@ssd.csd.harris.com (Tom Horsley) writes:
>>  [Henry Spencer says to make your identifiers unique in
>>   the first six characters.]
>  I have freedom of choice. I can refuse to work on systems
>  so brain dead they only support 6 character externals,
>  and I urge all other programmers to make the same choice.

Heh.  You know, I heard somewhere that shops with old,
crufty linkers pay their consulting fees in money that is
just as green as that paid out by shops with new, shiny
linkers.

Just a rumor, you understand.
--

 In some sense a stochastic process can do better; at least it has a chance.
Mark-Jason Dominus 	  			    mjd@central.cis.upenn.edu 

gwyn@smoke.brl.mil (Doug Gwyn) (11/07/90)

In article <TOM.90Nov5072220@hcx2.ssd.csd.harris.com> tom@ssd.csd.harris.com (Tom Horsley) writes:
>Not true. I have freedom of choice. I can refuse to work on systems so brain
>dead they only support 6 character externals, and I urge all other
>programmers to make the same choice.

Surely there are more important factors determining where to work than that.