100%(1)100% found this document useful (1 vote) 998 views181 pagesElements of Programming Style
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
THE
ELEMENTS
OF
PROGRAMMING
STYLE
SSEOOND EDITION,
Kernighan and PlaugerTHE
ELEMENTS
OF
PROGRAMMING
Brian W. Kernighan
Bell Laboratories
Murray Hill, New Jersey
P. J. Plauger
Yourdon, Inc.
‘New York, New York
McGRAW-HILL BOOK COMPANY
New York St. Lowy Sun Frimcnco Auckland Bogoti Dusseldorf
London Madrid Mexico Montreal New Delhy
Panama Pans Sio Paulo Singapore Sydney Tokyo TorontoLibrary of Congress Cataloging in Publication Data
Kernighan, Brian W.
The elements of programming style
Bibliography: p.
Includes index
1. Electonic digital computers— Programming
1, Plauger, PJ, date joint author.
U. Tile
(QA76.6.K47 1978 001.642 78-3498
ISBN 0.07-038207-5,
The Elements of Programming Style
Copyright © 1978, 1974 by Bell Telephone Laboratories, Incorporated,
All rights reserved. No part of this publication may be reproduced, stored in a retrieval
system, or transmitted, in any form or by any means, elecronic, mechanical, photocopy-
ing, recording, or otherwise, without the prior written permission of Bell Laboratories.
Printed in the United States of America,
12131415 D0D089
This book was set in Times Roman and Courier 12 by the authors, using a Graphic Sys-
tems phototypesetter driven by a PDP-11/70 running under the UNIX opera
UNIX isa Trademark of Bell Laboratories.We are deeply indebted to the following authors and publishers for their kind permission
to reproduce excerps from the following copyrighted materi
AV And. 1 P Andee and D Andes, Cony Popmmag Tengu, Anais, ad Maneater Capit ©
197} wy RT Andee By petson of rn Ie
aes nd ML, Dou, Progamming Lain th Scared Pepenm (The Eton) Copy ©1918 by
Frente a, ne" Repte perms
LR Began en fac Fan IVm War & Wat Cait 1 y Ads ey ating Co
E.R fe AF Fea, ad DA Gomi, Boe PLE Pram. Com © 6b Aion Ney Pig
Moh and Wale, fot PL Poprammne and PLC: Copy © 191 by Seca Rese ASS, I
Reged mina of he poser
V1 alent 4 Cos on Panag Fran Contig © 1969 by Chipman ad Hal, Lig By erin
ul M Chita, adicion Famer IY Coprah © 173 by Academic Pet By german
Frank) Cla, Jrodionw Lf Prams Copyah © 1971 by Aland Bacon. ee By perminion
Congr Copan © 1972 by Compara Neon Mss 260 permision
Danmar Copii © 1972 197 Techn Posing Compey. Green, Conte O60. Repent ih pe
DF Deta, Prong of Fores Pagammag. Capris © 1972 by W A Beni, nc, Mes Pat Calor By pe
Piso fe pusher
Dit, tedon Comgune Cont © 197, Hen Diner By perminon The Macmilan Compan, New Yo
© Dean Mr tn ema Pct Conia Ria sd Wins, 186 By
VT Desk, nan Pram, Cony © 1972 by Ren Pabiing Company Ine By prmiion
WS Dorn, GG bier, ad DL Hear, Compu Apion fr Catuha Captih © Pind, Weds & Som, Ie
1572 Bysemaioe
WS,Deg snd Mc, Nm Md mt Forme Ca Sd Cara © 1972 yn Wi Sos,
LE anus, PL fr Bases Acton Cony © 1973 by Reson Pubiing Com, ns By permis
M Fan, Fran 1 Sees Copy © Pie Hel ne 198 By persion
1S Gonfes,Pgammng we Fran V Copy © 1872 y Quantum Piss. ne By germision
abil F Groner Pt Pram Techn Aplaons. Copy © 171 by John Wey ané Sons. Ic Reine
‘Sr eminon of epee
1 a, Compete Sener Fran Poammay, Conrigh © Hayden ook Company, Inc 1989 By permiin
1 Hughes Lt Pogammag, Coprih © 173 by Jobe Wie & Son, ne By permaion
1. Manes 1 Mido. 4 Sched Arch Pvemmrs Conrigh © 197 by Pea a Ine Repine by
ALL Arete Ta, erin wn PL Poe Ge Capi © yh
€)8 Rte an 8 Siem, Tie hme rn Sk Cay © 17 Hu Bc ono eB
11 Kucera H Mee, ntmation Teche wh Fran Copa © 1973 by MeGre il ney permission
5.5 Kuo. Comper Aan of Numer! Mee Conrigh © Asin Wes Pabishing Compu. 1972 By perm
HL Leder, Prams Ponts Cape ©1975 Hayden Bok Company By sermon
2S Lely, Far 1Y Pram Cope © MiG, ne, 196 By prion
(0 Mant, Caton Wah Forman Capri © 191 by Cher E Merl Paling Co Ine By perminion
WA Manning sR S Creer, 4 Foren IF Poem Ser. Con © McGrew ne 1970 By pemion
Muna D Hato. Eke f Crp Povammve Foran Copy ©1973 Pablhe by Delma Pabst
Shson a itn Ec abhi. ney prmsion
2 MeCattn, «Gade Fran 1 Parone Capi © 145 ha Wiky An Sos Me Rep ypVi THE ELEMENTS OF PROGRAMMING STYLE
1D McCracken, 4 Gu w Fry IV Prramm. Scand Eton Copan © 1872 John Wiy and Sons. nee
Piste permis the pte
CL Moun ad Keb, ToD Src aan ech Conrih © 95 Ln Edt a
LP Mester, The Seem of Coie Capi ©1974 by Wasavonh Pubs Company I By mise
Matin, Madr Pram Fran IY Copy © 1968 by Jn Wey & Sms. Ine By ptmisnn
au Marl an CooL Sih eran Prams Emr nd Se. Send ten) Cah ©
au rad Cat, Sh PL Pam ine) Coit 19 by pes & Roe Pe ac Un by
RL Nolin, Faw 1F Comput ad Aplcnons Cony © Addaoe Wey Posing Company. 1971 By prion
| Oppni and LP Mesues, Faron IV (Sond Eo Cori © 1974 by Adon Ney Pbtaing Compr,
Inc By prion
5 ¥ Potuck, Gnd Fran Copia © Columba Untery Pes. 9658) permison
Seymoue ¥ Polack ant Theodor O Sie. 4 Gas PLT Coptht © 149 by Ho. Richa en Wison Re
Pmmaton a Rinna sa Winton
Syma V Plick nd Thode D Sting 4 Gude PL Sind Eso) Conia © 1975 Hol, Rina sn Wie
Seymour ¥ Police ad Toor D String, Exe of PLT Coprih © 19 by Ho Rind and Wison Reine
‘pmo oak Rn ond Wine
1 Ration. Foren Promo, Con Epon Cony © MeGron il In, 197 By perio
G1 Renan dS Bin, Ponam Sohing Une PLC Cony © 1975 by bn Wit Sos Ie Bypermsion
2S Roper, PL Ean Stes Contig © 197 by Pl lk Seti Boos Lid By pein
WP Rate Forran YPrammne Cony © 1968) W P Kale Fee, Weber & Smt. oe By pemision
Stoo Maer Suly Cron, terms. Conger and Mahmut Fran Sunt Se ex Red Eon)
Spratt © SunordUnversy6e” By Pesan No edoemen y SSG plod
Gt Set and 3 Set, PLL 4 Sao! Manual Capt © 18 by Dekenon Paling Comma Byrne
RC ScaantN E Sond PLi fo Pannen Capri © Adon Wey Pbishing Company. 190 By yemisson
Dual D Snr, Pent 4 Sen Fre antFren Cony © 1 Xe Copion Uy
DD Ser Conn en Pont Gn Fo Emr oni © 13 Hows W Se Aone
1 C Sproml, Jerson PL Prparmne Cope © 1989 by Harpe & Row abies. Ine By pemison
RA Stem ana 8 Sern, Prep DaePceae Copia © 173 by Jobe Wiley & Sos In By pein
F Sturt Faron Prnammng Capih © 199 by Fei Sart Rept by mono he Wik and Son. ne
4, Soy Pn SD Con wet Pomme 8 Pee I, 70 emi.
Maes an WW Cea 4nd Cong Smead Aer Pres. Comrih © 17by Albn
(0 M Weeden. PL Progamming 4 MomalfSle Conran © McGnw-Hi Ic. 1970 By pemissonPreface to the Second Edition
Preface to the First Edition
Introduction
Expression
Control Structure
Program Structure
Input and Output
Common Blunders
Efficiency and Instrumentation
Documentation
Epilogue
Supplementary Reading
Summary of Rules
Index
CONTENTS:
101
123
141
155
157
159
163,PREFACE to the Second Edition
The practice of computer programming has changed since The Elements of Pro-
gramming Style first appeared. Programming style has become @ legitimate topic of
discussion. After years of producing “write-only code,” students, teachers, and
computing professionals now recognize the importance of readable programs. There
hhas also been a widespread acceptance of structured programming as a valuable cod-
ing discipline, and a growing recognition that program design is an important phase,
too often neglected in the past
We have revised The Elements of Programming Style extensively to reflect these
changes. The first edition avoided any direct mention of the term “structured pro-
gramming,” to steer well clear of the religious debates then prevalent. Now that the
fervor has subsided, we feel comfortable in discussing structured coding techniques
that actually work well in practice.
The second edition devotes a whole new chapter to program structure, showing
how top-down design can lead to better organized programs. Design issues are dis-
cussed throughout the text. We have made considerable use of pseudo-code as a
program development tool
We have also rewritten many of the examples presented in the first edition, to
reflect (we hope) a greater understanding of how to program well. There are new
examples as wel, including several from the first edition which now serve as models
fof how nor to do things. New exercises have been added. Finally, we have
extended and generalized our rules of good styl.
We are once again indebted to the authors and publishers who have graciously
given us permission to reprint material from their textbooks. Looking back on some
of our on examples makes us realize how demanding an effort good programming
is.
We would also like to thznk friends who read the second edition in draft form.
In particular, Al Aho, Jim Blue, Stu Feldman, Paul Kernighan, Doug Meliroy,
Ralph Muha, and Dick Wexelblat provided us with valuable suggestions.
Brian W. Kernighan
P.J. PlaugerPREFACE to the First Edition
Good programming cannot be taught by preaching generalities. The way to
learn to program well is by seeing, over and over, how real programs can be
improved by the application of a few principles of good practice and a little common
sense. Practice in critical reading leads to skill in rewriting, which in turn leads to
better writing,
This book is a study of a large number of “real” programs, each of which pro-
vides one or more lessons in style. We discuss the shortcomings of each example,
rewrite it in a better way, then draw a general rule from the specific case. The
approach is pragmatic and down-to-earth; we are more interested in improving
‘current programming practice than in setting up an elaborate theory of how pro-
gramming should be done. Consequently, this book can be used as a supplement in
2 programming course at any level, or as a refresher for experienced programmers.
‘The examples we give are all in Fortran and PL/I, since these languages are
widely used and are sufficiently similar that a reading knowledge of one means that
the other can also be read well enough. (We avoid complicated constructions in
either language and explain unavoidable idioms as we encounter them.) The princi=
piles of style, however, are applicable in all languages, including assembly codes.
Our aim is to teach the elements of good style in a small space, so we concen-
trate on essentials. Rules are laid down throughout the text to emphasize the les-
sons learned. Each chapter ends with a summary and @ set of “points to ponder,”
which provide exercises and a chance to investigate topics not fully covered in the
text itself. Finally we collect our rules in one place for handy reference.
‘A word on the sources of the examples: all of the programs we use are taken
from programming textbooks. Thus, we do not set up artificial programs to illus:
trate our points — we use finished products, written and published by experienced
Programmers. Since these examples are typically the first code seen by a novice pro-
grammer, we would hope that they would be models of good style. Unfortunately,
we Sometimes find that the opposite is true — textbook examples often demonstrate
the state of the art of computer programming all too well, (We have done our best
to play fair — we don’t think that any of the programs are made to look bad by
being quoted out of context.)
Let us state clearly, however, that we intend no criticism of textbook authors,
either individually or as a class. Shortcomings show only that we are all human, and
that under the pressure of a large, intellectually demanding task like writing a pro-
{gram of a book, it is much too easy to do some things imperfectly. We have noji THE ELEMENTS OF PROGRAMMING STYLE.
doubt that a few of our “good” programs will provide “bad” examples for some
future weiter — we hope only that he and his readers will learn from the experience
of studying them carefully,
‘A manual of programming style could not have been written without the
pioneering work of numerous people, many of whom have written excellent pro-
gramming textbooks. D. D. McCracken and G. M. Weinberg, for instance, have
Tong taught the virtues of simplicity and clarity. And the work of E. W. Dijkstra and
Harlan Mills on structured programming has made possible our rules for properly
specifying flow of control. The form and approach of this book has been strongly
influenced by The Elements of Style by W. Strunk and E. B. White. We have tried to
emulate their brevity by concentrating on the essential practical aspects of styl.
We are indebted to many people for their help and encouragement, We would
like especially to thank the authors and publishers who gave us permission to repro-
duce the computer programs used in this text. Their cooperation is greatly appreci-
ated.
‘Our friends and colleagues at Bell Laboratories provided numerous useful
suggestions, which we have incorporated, and saved us from more than one embar-
rassing blunder, which we have deleted. In particular, V. A. Vyssotsky bore with us
through several revisions; for his perceptive comments and enthusiastic support at
every stage of this book's evolution (and for several aphorisms we have shamelessly
stolen) we are deeply grateful. We would also like to single out A. V. Aho, M. E.
Lesk, M. D. Mcllroy, and J. S. Thompson for the extensive time and assistance they
gave to this project.
We were able to type the manuscript directly into a PDP 11/45, edit the source,
check the programs, and set the final version in type — all with the help of a
uniquely Nexible operating system called UNIX. K. L. Thompson and D. M. Ritchie
were the principal architects of UNIX; besides reading drafts, they helped us get the
most out of the system while we were working on this book. J. F. Ossanna wrote
the typesetting program and made several modifications for our special needs. We
thank them.
Brian W. Kernighan
PJ. PlaugerTHE
ELEMENTS
oF
PROGRAMMING
STYLECHAPTER 1: INTRODUCTION
Consider the program fragment
bo 14 rt 48,
Do 14 Jat x
14 Viz, 3) (1/94 19/2)
‘A modest familiarity with Fortran tells us that this doubly nested DO loop assigns
Something to each element of an N by N matrix V. What are the values assigned? T
and J are positive integer variables and, in Fortran, integer division truncates
toward zero. Thus when T is less than J, (I/3) is zero; conversely, when J is less
than 1, (3/1) is zero. When 1 equals J, both factors are one. So (I/3)#(3/2)
is one if and only if x equals J: otherwise itis zero. The program fragment puts
‘ones on the diagonal of V and zeros everywhere else. (V becomes an identity
matrix.) How clever!
Or is it?
Suppose you encountered this fragment in a larger program. If your knowledge
of Fortran is sufficiently deep, you may have enjoyed the clever use of integer divi
sion. Possibly you were appalled that two divisions, a multiplication, and a conver-
sion from integer to floating point were invoked’ when simpler mechanisms are
available. More likely, you were driven to duplicating the reasoning we gave above
to understand what is happening. Far more likely, you formed @ vague notion that
something useful is being put into an array and simply moved on. Only if motivated
strongly, perhaps by the need to debug or to alter the program, would you be likely
to go back and puzzle out the precise meaning
‘A better version of the fragment is
Dot T= 18
powssiN
12 ving) ='0.0
14 va,n'= 10
This zeros each row, then changes its diagonal element to one. The intent is now
reasonably clear, and the code even happens to execute faster. Had we been pro-
gramming in PL/I, we could have been more explicit:2. THE ELEMENTS OF PROGRAMMING STYLE. CHAPTER 1
(+ MAKE V AN IDENDITY MATRIX «/
= 0.0;
varn) = 10;
In either case, it is more important to make the purpose of the code unmistak-
able than to display virtuosity. Even storage requirements and execution time are
‘unimportant by comparison, for setting up an identity matrix must surely be but a
small part of the whole program. The problem with obscure code is that debugging
and modification become much more difficult, and these are already the hardest
aspects of computer programming. Besides, there is the added danger that a t00-
clever program may not say what you thought it said
Write clearly — don't be 100 clever.
Let’s pause for a moment and look at what we've done. We studied part of a
program, taken verbatim from a programming textbook, and discussed what was
good about it and what was bad. Then we made it better. (Not necessarily perfect
= just better.) And then we drew a rule or a general conclusion from our analysis
and improvements, a rule that would have sounded like a sweeping generality in the
abstract, but which makes sense and can be applied once you've seen a specific case,
‘The rest of the book will be much the same thing — an example from a text,
discussion, improvements, and a rule, repeated over and over. When you have
finished reading the book, you should be able to criticize your own code. More
important, you should be able to write it better in the first place, with less need for
criticism.
‘We have tried to sort the examples into a logical progression, but as you shall
see, real programs are like prose — they often violate simultaneously a number of
rules of good practice. Thus our classification scheme may sometimes seem arbi-
trary and we will often have to digress.
‘Most of the examples will be bigger than the one we just saw, but not exces-
sively so; with the help of our discussion, you should be able to follow them even if
you're a beginner. In fact, most of the bigger programs will shrink before your very
eyes as we modify them. Sheer size is often an illusion, reflecting only a need for
improvement
‘The examples are all in either Fortran or PL/I, but if one or both of these
languages is unfamiliar, that shouldn't intimidate you any more than size should.
Although you may not be able to write a PL/I program, say, you will certainly be
able to read one well enough to understand the point we are making, and the prac-
tice in reading will make learning PL/I that much easier.
For example, here is a small part of a PL/I program that we will discuss in
detail in Chapter 4: