⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 http:^^www.cs.princeton.edu^courses^cs217^etc^pike.html

📁 This data set contains WWW-pages collected from computer science departments of various universities
💻 HTML
📖 第 1 页 / 共 2 页
字号:
Server: Netscape-Commerce/1.12
Date: Tuesday, 14-Jan-97 20:21:08 GMT
Last-modified: Wednesday, 23-Oct-96 15:46:32 GMT
Content-length: 16445
Content-type: text/html

<HEADER><title>Notes on Programming in C</title></HEADER><BODY><H1>Notes on Programming in C</H1><address>Rob Pike, AT&T Bell Laboratories</address><h2>Introduction</h2>Kernighan and Plauger's<cite>The Elements of Programming Style</cite> (Prentice Hall, 1978)was an important and rightly influential book.But sometimes I feel its concise rules were taken as a cookbookapproach to good style instead of the succinct expression of a philosophythey were meant to be.If the book claims that variable names should be chosenmeaningfully, doesn't it then follow that variables whose names aresmall essays on their use are even better?Isn't<tt>MaximumValueUntilOverflow</tt>a better name than<tt>maxval</tt>?I don't think so.<p>What follows is a set of short essays that collectivelyencourage a philosophy of clarity in programming rather thangiving hard rules.I don't expect you to agree with all of them,because they are opinion and opinions change with the times.But they've been accumulating in my head, if not on paperuntil now, for a long time, and are based on a lot of experience,so I hope they help you understandhow to plan the details of a program.(I've yet to see a good essay on how to plan the whole thing.)If you find them idiosyncratic, fine;if you disagree with them, fine;but if they make you think about why you disagree, that's better.Under no circumstances should you program the way I say tobecause I say to; program the way you think expresses bestwhat you're trying to accomplish in the program.And do so consistently and ruthlessly.<p>Your comments are welcome.<p><h2>Issues of typography</h2>A program is a sort of publication.It's meant to be read by the programmer,another programmer (perhaps yourself a few days, weeks or years later),and lastly a machine.The machine doesn't care how pretty the program is -if the program compiles, the machine's happy -but people do, and they should.Sometimes they care too much: pretty printersmechanically produce pretty output that accentuates irrelevant detail inthe program, which is<b>as</b>sensible<b>as</b>putting all the prepositions<b>in</b>English text<b>in</b>bold font.Although many people think programs should look like the Algol-68 report(and some systems even require you to edit programs in that style),a clear program is not made any clearer by such presentation,and a bad program is only made laughable.<p>Typographic conventions consistently heldare important to clear presentation, of course -indentation is probably the best known and most useful example -but when the ink obscures the intent, typography has taken over.So even if you stick with plain old typewriter-like output, be consciousof typographic silliness.Avoid decoration; for instance,keep comments brief and banner-free.Say what you want to say in the program, neatly and consistently.Then move on.<p><h2>Variable names</h2>Ah, variable names.Length is not a virtue in a name;clarity of expression<em>is</em>.A global variable rarely used may deserve a long name,<tt>maxphysaddr</tt>say. An array index used on every line of a loop needn't be namedany more elaborately than<tt>i</tt>.Saying<tt>index</tt>or<tt>elementnumber</tt>is more to type (or calls upon your text editor) and obscuresthe details of the computation.When the variable names are huge, it's harder to see what's going on.This is partly a typographic issue; consider<pre>for(i=0 to 100)	array[i]=0</pre>vs.<pre>for(elementnumber=0 to 100)	array[elementnumber]=0;</pre>The problem gets worse fast with real examples.Indices are just notation, so treat them as such.<p>Pointers also require sensible notation.<tt>np</tt>is just as mnemonic as<tt>nodepointer</tt><em>if</em>you consistently use a naming convention from which<tt>np</tt>means `node pointer' is easily derived.More on this in the next essay.<p>As in all other aspects of readable programming, consistency is importantin naming. If you call one variable<tt>maxphysaddr</tt>,don't call its cousin<tt>lowestaddress</tt>.<p>Finally, I prefer minimum-length but maximum-information names, andthen let the context fill in the rest.Globals, for instance, typically have little context when they are used,so their names need to be relatively evocative. Thus I say<tt>maxphysaddr</tt>(not<tt>MaximumPhysicalAddress</tt>)for a global variable, but<tt>np</tt>not<tt>NodePointer</tt>for a pointer locally defined and used.This is largely a matter of taste, but taste is relevant to clarity.<p>I eschew embedded capital letters in names; to my prose-oriented eyes,they are too awkward to read comfortably. They jangle like bad typography.<p><h2>The use of pointers</h2>C is unusual in that it allows pointers to point to anything.Pointers are sharp tools, and like any such tool, used wellthey can be delightfully productive, but used badly they cando great damage (I sunk a wood chisel into my thumba few days before writing this).Pointers have a bad reputation in academia,because they are considered too dangerous, dirty somehow.But I think they are powerful<em>notation</em>,which means they can help us express ourselves clearly.<p>Consider: When you have a pointer to an object, it is a name for exactlythat object and no other. That sounds trivial, but look at the followingtwo expressions:<pre>npnode[i]</pre>The first points to a node, the second evaluates to (say) the same node.But the second form is an expression; it is not so simple.To interpret it, we must know what<tt>node</tt>is, what<tt>i</tt>is, and that<tt>i</tt>and<tt>node</tt>are related by the (probably unspecified) rulesof the surrounding program.Nothing about the expression in isolation can show that<tt>i</tt>is a valid index of<tt>node</tt>,let alone the index of the element we want.If<tt>i</tt>and<tt>j</tt>and<tt>k</tt>are all indices into the node array, it's very easy to slip up,and the compiler cannot help.It's particularly easy to make mistakes when passing things to subroutines:a pointer is a single thing; an array and an index must be believedto belong together in the receiving subroutine.<p>An expression that evaluates to an object is inherently more subtleand error-prone than the address of that object.Correct use of pointers can simplify code:<pre>parent->link[i].type</pre>vs.<pre>lp->type.</pre>If we want the next element's type, it's<pre>parent->link[++i].type</pre>or<pre>(++lp)->type.</pre><tt>i</tt>advances but the rest of the expression must stay constant;with pointers, there's only one thing to advance.<p>Typographic considerations enter here, too.Stepping through structures using pointers can be mucheasier to read than with expressions: less ink is needed andless effort is expended by the compiler and computer.A related issue is that the type of the pointer affects how itcan be used correctly, which allows some helpful compile-time errorchecking that array indices cannot share.Also, if the objects are structures, their tag fields arereminders of their type, so<pre>np->left</pre>is sufficiently evocative; if an array is being indexed the arraywill have some well-chosen name and the expression will end uplonger:<pre>node[i].left.</pre>Again, the extra characters become more irritating as the examplesbecome larger.<p>As a rule, if you find code containing many similar, complex expressionsthat evaluate to elements of a data structure, judicious use ofpointers can clear things up.Consider what<pre>if(goleft)	p->left=p->right->left;else	p->right=p->left->right;</pre>would look like using a compound expression for<tt>p</tt>.Sometimes it's worth a temporary variable (here<tt>p</tt>)or a macro to distill the calculation.<p>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -