% X-NEWS: spcvxb vmsnet.internals: 2406 T Relay-Version: VMS News - V6.1B7+SPC1,2 05/22/93 VAX/VMS V5.5-2; site spcvxb.spc.edue Path: spcvxb!uunet!noc.near.net!howland.reston.ans.net!wupost!waikato.ac.nz!comp.vuw.ac.nz!zl2tnm!don  Newsgroups: vmsnet.internals/ Subject: The Ten Commandments for C Programmers 1 Message-ID: <1993May27.122637.2299@zl2tnm.gen.nz>  From: don@zl2tnm.gen.nz  Date: 27 May 93 12:26:37 +1300 Organization: The Wolery
 Lines: 377   I quoted from:  7 >     The Ten Commandments for C Programmers (Annotated # >                          Edition) % >                       Henry Spencer   B and instantly, my mailbox runneth over with requests for the full H version.  OK, it's not internals, but it's still good advice.  Here are:    6      The Ten Commandments for C Programmers (Annotated"                           Edition)    $                        Henry Spencer            < 1    Thou shalt run lint frequently and study its pronounce-<      ments  with  care, for verily its perception and judge-      ment oft exceed thine. 2                This   is   still   wise   counsel,2                although   many   modern  compilers2                search out many of the  same  sins,2                and  there  are often problems with2                lint being aged and infirm, or una-2                vailable  in  strange lands.  There2                are other tools, such  as  Saber C,&                useful to similar ends.2                ``Frequently'' means thou  shouldst2                draw  thy  daily  guidance from it,2                rather than hoping  thy  code  will2                achieve lint's blessing by a sudden2                act  of  repentance  at  the   last2                minute.  De-linting a program which2                has never  been  linted  before  is2                often  a  cleaning  of  the stables2                such as thou wouldst  not  wish  on2                thy  worst  enemies.  Some observe,2                also,  that  careful  heed  to  the2                words  of lint can be quite helpful                in debugging.2                ``Study'' doth  not  mean  mindless2                zeal  to  eradicate  every  byte of2                lint output-if for no other reason,2                because thou just canst not shut it2                up about some things-but that  thou2                should know the cause of its unhap-2                piness and understand  what  worri-.                some sign it tries to speak of.  < 2    Thou shalt not follow the NULL pointer, for  chaos  and#      madness await thee at its end. 2                Clearly the  holy  scriptures  were2                mis-transcribed  here, as the words2                should have been ``null  pointer'',2                to  minimize  confusion between the2                concept of null  pointers  and  the2                macro  NULL  (of  which more anon).2                Otherwise, the meaning is plain.  A2                null   pointer  points  to  regions2                filled with dragons,  demons,  core2                dumps,  and  numberless  other foul2                creatures, all of which delight  in2                frolicing  in  thy  program if thou2                disturb  their   sleep.    A   null2                pointer  doth  not  point to a 0 of2                any type, despite some  blasphemous2                old  code  which  impiously assumes                this.  < 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.2                A programmer should understand  the2                type  structure  of  his  language,0                lest great misfortune befall him.2                Contrary to the  heresies  espoused2                by  some  of  the  dwellers  on the2                Western Shore, `int' and `long' are2                not  the  same type.  The moment of2                their  equivalence  in   size   and2                representation  is  short,  and the2                agony  that  awaits  believers   in      &                      November 25, 1992                                       - 2 -    2                their interchangeability shall last2                forever  and   ever   once   64-bit&                machines become common.2                Also, contrary to the beliefs  com-2                mon among the more backward inhabi-2                tants  of  the   Polluted   Eastern2                Marshes,  `NULL'  does  not  have a2                pointer type, and must be  cast  to2                the  correct  type  whenever  it is+                used as a function argument. 2                (The words  of  the  prophet  Ansi,2                which  permit NULL to be defined as2                having the type `void *',  are  oft2                taken  out of context and misunder-2                stood.  The prophet was granting  a2                special  dispensation  for  use  in2                cases of  great  hardship  in  wild2                lands.  Verily, a righteous program2                must make its own way  through  the2                Thicket  Of  Types  without  lazily2                relying  on  this  rarely-available2                dispensation to solve all its prob-2                lems.   In  any  event,  the  great2                deity Dmr who created C hath wisely2                endowed  it  with  many  types   of2                pointers, not just one, and thus it2                would still be necessary to convert2                the  prophet's  NULL to the desired                type.) 2                It may be thought that the  radical2                new   blessing   of  ``prototypes''2                might eliminate the need  for  cau-2                tion about argument types.  Not so,2                brethren.  Firstly, when confronted2                with  the  twisted  strangeness  of2                variable numbers of arguments,  the2                problem  returns...  and he who has2                not  kept  his  faith   strong   by2                repeated practice shall surely fall2                to this subtle trap.  Secondly, the2                wise  men  have observed that reli-2                ance on prototypes doth  open  many2                doors  to  strange errors, and some2                indeed had  hoped  that  prototypes2                would  be  decreed  for purposes of2                error checking but would not  cause2                implicit    conversions.    Lastly,2                reliance  on   prototypes   causeth2                great  difficulty in the Real World2                today, when many cling to  the  old2                ways  and  the old compilers out of2                desire or  necessity,  and  no  man2                knoweth  what  machine his code may+                be asked to run on tomorrow.   < 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.2                The prophet Ansi,  in  her  wisdom,2                hath  added that thou shouldst also2                scourge thy Suppliers,  and  demand2                on  pain  of  excommunication  that2                they  produce  header  files   that2                declare  their  library  functions.2                For truly, only they know the  pre-2                cise   form   of   the  incantation2                appropriate to invoking their magic"                in the optimal way.2                The  prophet  hath  also  commented2                that  it  is  unwise, and leads one2                into the pits of damnation and sub-2                tle  bugs,  to  attempt  to declare2                such  functions  thyself  when  thy-                header files do the job right.   < 5    Thou shalt  check  the  array  bounds  of  all  strings<      (indeed,  all  arrays),  for  surely  where thou typest<      ``foo'' someone someday shall type ``supercalifragilis-      ticexpialidocious''.n2                As demonstrated by the deeds of the2                Great  Worm,  a consequence of this2                commandment is that robust  produc-2                tion software should never make use2                of gets(), for it is truly  a  tool2                of   the   Devil.   Thy  interfaces2                should always inform  thy  servants2                of  the  bounds  of thy arrays, and2                servants who spurn such  advice  or2                quietly fail to follow it should be2                dispatched forthwith to the Land Of2                Rm,  where  they  can do no further                harm to thee.  < 6    If a function be advertised to return an error code  in<      the  event  of  difficulties, thou shalt check for that    &                      November 25, 1992                                       - 3 -    <      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  gods0      shall surely punish thee for thy arrogance.2                All true believers doth wish for  a2                better   error-handling  mechanism,2                for explicit checks of return codes2                are tiresome in the extreme and the2                temptation to omit them  is  great.2                But   until   the  far-off  day  of2                deliverance cometh, one  must  walk2                the  long  and  winding  road  with2                patience and care, for thy  Vendor,2                thy   Machine,   and  thy  Software2                delight  in  surprises  and   think2                nothing  of  producing subtly mean-2                ingless results on the  day  before2                thy Thesis Oral or thy Big Pitch To                The Client.2                Occasionally, as with the  ferror()2                feature of stdio, it is possible to2                defer error checking until the  end2                when  a  cumulative  result  can be2                tested, and  this  often  produceth2                code  which is shorter and clearer.2                Also, even the most  zealous  beli-2                ever should exercise some judgement2                when dealing with  functions  whose2                failure is totally uninteresting...2                but beware, for the cast to void is2                a  two-edged  sword  that  sheddeth/                thine own blood without remorse.m  < 7    Thou shalt study thy libraries and strive  not  to  re-<      invent  them  without cause, that thy code may be short7      and readable and thy days pleasant and productive.n2                Numberless are the unwashed heathen2                who  scorn their libraries on vari-2                ous  silly  and  spurious  grounds,2                such as blind worship of the Little2                Tin  God  (also  known  as  ``Effi-2                ciency'').   While  it is true that2                some features of  the  C  libraries2                were  ill-advised,  by and large it2                is better and cheaper  to  use  the2                works  of others than to persist in2                re-inventing the square wheel.  But2                thou  should  take  the greatest of2                care   to   understand   what   thy2                libraries promise, and what they do2                not, lest thou rely  on  facilities2                that may vanish from under thy feet                in future..  < 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 creating0      beautiful new impediments to understanding.2                These words, alas, have caused some2                uncertainty  among  the novices and2                the converts, who knoweth  not  the2                ancient   wisdoms.   The  One  True2                Brace Style  referred  to  is  that2                demonstrated in the writings of the2                First   Prophets,   Kernighan   and2                Ritchie.   Often  and  again  it is2                criticized by the ignorant as  hard2                to  use, when in truth it is merely2                somewhat difficult  to  learn,  and2                thereafter is wonderfully clear and2                obvious, if perhaps a bit sensitive                to mistakes.e2                While thou might think  that  thine2                own  ideas  of  brace style lead to2                clearer  programs,  thy  successors2                will  not  thank  thee  for it, but2                rather shall revile thy  works  and2                curse  thy  name,  and word of this2                might get  to  thy  next  employer.2                Many  customs  in this life persist2                because they ease friction and pro-2                mote  productivity  as  a result of2                universal  agreement,  and  whether2                they   are  precisely  the  optimal2                choices is much less important.  So&                it is with brace style.2                As a lamentable side  issue,  there2                has   been  some  unrest  from  the2                fanatics  of  the  Pronoun  Gestapo2                over the use of the word ``man'' in2                this Commandment, for they  believe2                that  great efforts and loud shout-2                ing   devoted   to    the    ritual      &                      November 25, 1992                                       - 4 -    2                purification  of  the language will2                somehow redound to the  benefit  of2                the  downtrodden  (whose  real  and2                grievous woes tendeth to  get  lost2                amidst  all that thunder and fury).2                When preaching the  gospel  to  the2                narrow of mind and short of temper,2                the word ``creature'' may  be  sub-2                stituted as a suitable pseudoBibli-2                cal term free of the taint of  Pol-$                itical Incorrectness.  < 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.2                Though some hasty zealots cry ``not2                so; the Millenium is come, and this2                saying is obsolete  and  no  longer2                need  be  supported'', verily there2                be many, many  ancient  systems  in2                the  world, and it is the decree of2                the dreaded  god  Murphy  that  thy2                next  employment  just  might be on2                one.  While thou sleepest, he plot-2                teth  against thee.  Awake and take                care.2                It is, note carefully,  not  neces-2                sary  that  thy identifiers be lim-2                ited to a length of six characters.2                The  only requirement that the holy2                words place upon thee is uniqueness2                within  the  first six.  This often2                is not so hard  as  the  belittlers                claimeth.  < 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.2                This particular heresy bids fair to2                be  replaced by ``All the world's a2                Sun'' or ``All the world's a  386''2                (this  latter  being a particularly2                revolting invention of Satan),  but2                the words apply to all such without2                limitation.  Beware, in particular,2                of  the  subtle  and terrible ``All2                the  world's  a  32-bit  machine'',2                which  is  almost  true  today  but2                shall cease to  be  so  before  thy,                resume grows too much longer.  &                      November 25, 1992      O Don Stokes, CSC Network Manager, Victoria University of Wellington, New ZealandiO Ph+64 4 495-5052  Fax+64 4 471-5386  Work:don@vuw.ac.nz  Home:don@zl2tnm.gen.nz 