nelson@sun.soe.clarkson.edu (Russ Nelson) (12/06/88)
I know, this is a religious question. However, I would like to know if anyone has codified a standard for indentation of C programs? -- --russ (nelson@clutx [.bitnet | .clarkson.edu]) To surrender is to remain in the hands of barbarians for the rest of my life. To fight is to leave my bones exposed in the desert waste.
fransvo@htsa (Frans van Otten) (12/06/88)
In article <NELSON.88Dec5142722@sun.soe.clarkson.edu> nelson@clutx.clarkson.edu writes: >I know, this is a religious question. However, I would like to know if >anyone has codified a standard for indentation of C programs? There seems to be a de-facto standard, to which I stronly disagree. I'll just explain my style: #define then /* as white space; see below */ int func(a, b, c) int a; char b; double c; { if (c > 3.0e10) printf("big\n"); while (a > 2) { putchar(b); putchar(c); if (a > 10) then putchar('1'); else putchar('2'); } } 1. then must be defined (as white space) because the then-action must be at the same level as the else-action. Some people dis- agree with this, but look at it this way: *every* if-statement can be rewritten into a switch-statement, and in that case, the then-action and the else-action are at the same level: if (expr) switch (expr) then stat1; { default: stat1; break; else stat2; case 0: stat2; break; } For shortness, if there is no else-action, you can always write the then-part (with or without the 'then') on the same line as the if (expr). This doesn't make the program less readable. 2. Indentation always by two spaces. A tab uses too much space. 3. Closing } always straight below opening {. It's easier to see where the compound-statement ends. 4. Main rule: something *within* something else *always* indented. You can easily see what belongs to what, which is the next state- ment, etc. I have been using this style for some years now. It has proved to me that it is far more readable then any other style I ever saw. It has proved useful debugging programs. -- Frans van Otten Algemene Hogeschool Amsterdam Technische en Maritieme Faculteit fransvo@htsa.uucp
usenet@cps3xx.UUCP (Usenet file owner) (12/06/88)
in article <NELSON.88Dec5142722@sun.soe.clarkson.edu>, nelson@sun.soe.clarkson.edu (Russ Nelson) says: > > I know, this is a religious question. However, I would like to know if > anyone has codified a standard for indentation of C programs? Last place I worked I drew up an informal internal C coding standard. So, I'm sure there are plenty of internal coding standars that address. K&R exhibits a consistent style, although they never really discuss it in depth. The closest I've seen to a "code"ified ;-) standard is GNU Emacs' C-mode and description in the manual. John H. Lawitzke UUCP: ...rutgers!mailrus!frith!fciiho!jhl Michigan Farm Bureau ...decvax!purdue!mailrus!frith!fciiho!jhl Insurance Group ...uunet!frith!jhl "What?!? Real computing at an insurance company?!? AND in Michigan!?!"
bengsig@orcenl.uucp (Bjorn Engsig) (12/06/88)
In article <NELSON.88Dec5142722@sun.soe.clarkson.edu>, nelson@sun.soe.clarkson.edu (Russ Nelson) writes: > I know, this is a religious question. However, I would like to know if > anyone has codified a standard for indentation of C programs? I have, my company standard is different, my previous company standard was also different, my neighbour, etc. etc. etc I wonder how long the discussion will live this time :-) -- Bjorn Engsig, ORACLE Europe \ / "Hofstaedter's Law: It always takes ..!uunet!mcvax!orcenl!bengsig X longer than you expect, even if you phone: +31 21 59 56 411 / \ take into account Hofstaedter's Law"
djones@megatest.UUCP (Dave Jones) (12/07/88)
From article <NELSON.88Dec5142722@sun.soe.clarkson.edu>, by nelson@sun.soe.clarkson.edu (Russ Nelson): > I know, this is a religious question. However, I would like to know if > anyone has codified a standard for indentation of C programs? Yes, it is a religious question, and yes there have been standards published. My suggestion is not to worry about it during the design phase. Let people use the style they are most comfortable with. When it is time to turn a release, run all the sources through a standard pretty-printer.
funkstr@ucscb.UCSC.EDU (-=/ Larry Hastings /=-) (12/07/88)
+-In article <NELSON.88Dec5142722@sun.soe.clarkson.edu>, +-nelson@sun.soe.clarkson.edu (Russ Nelson) wrote +---------- | | I know, this is a religious question. However, I would like to know if | anyone has codified a standard for indentation of C programs? | +---------- Ain't no such animal; never will be. In fact, the UNIX program indent(1) has more options than ls(1). One thing I might suggest... if you're still deciding on whatever standard YOU are going to use, you could lean towards something you could define with indent options. THAT way, whenever you are looking at someone else's code, (someone else who, of COURSE, completely disagrees with your style of indenting, to the point of distraction) you can run it through indent so it will suddenly become READABLE. There is also cb(1), the original C pretty printer, which (I believe) formats your program to the indentation standard that K&R uses. cb is generally more available than indent. Also, cb won't change your code at all; indent is known to mess around with comments and sometimes declarations. -- /|\ /|\ .. . . . . . . . . . . | |\| |\| .. . . . . . . . . . . |/|\|/|\|/|| _ _ _ _ |_| _ _ |_ -__ _ _ARPA: funkstr@ucscb.ucsc.EDU | |/| |/|L_ (_\( ( (_/ | |(_\_) (_ || )(_)_)UUCP: *!ucbvax!ucscb!funkstr \|/ \|/ larry / hastings _/ WORK: sun!acad!metaware!funkster MetaWare Incorporated Disclaimer: It was a bad day. "If any of your OSF force are caught or killed, the Secretary will deny any knowlege of your activities." --from the new Mission: Impractical
bph@buengc.BU.EDU (Blair P. Houghton) (12/08/88)
From article <NELSON.88Dec5142722@sun.soe.clarkson.edu>, by nelson@sun.soe.clarkson.edu (Russ Nelson): > I know, this is a religious question. However, I would like to know if > anyone has codified a standard for indentation of C programs? In My Egotistical Opinion, most people's C programs should be indented six feet downward and covered with dirt. --Blair "#define foo baz" -Obligatory obfuscation
cquenel@polyslo.CalPoly.EDU (Chris (i = --i++;) Quenelle) (12/08/88)
In article <641@htsa.uucp> fransvo@htsa.UUCP (Frans van Otten) writes: > >#define then /* as white space; see below */ > > if (a > 10) > then putchar('1'); > else putchar('2'); Bravo!! Me Too!! whenever the statements are blocks, I omit the then, though. I vote strongly for this. The symmetry scans very easily for me. --chris ------------------------------------------------------------------------------- | Chris Quenelle | Smart Mailers -> cquenel@polyslo.CalPoly.EDU | | Computer Systems Lab | Dumb Mailers -> !ucbvax!voder!polyslo!cquenel | | Cal Poly State Univ. |-------------------------------------------------| | San Luis Obispo, CA 93407 | My computer can beat up your computer. - Karl | ------------------------------------------------------------------------------- We demand rigidly defined areas of doubt and uncertainty! -- Vroomfondel
henry@utzoo.uucp (Henry Spencer) (12/09/88)
In article <1054@goofy.megatest.UUCP> djones@megatest.UUCP (Dave Jones) writes: >My suggestion is not to worry about it during the design phase. Let >people use the style they are most comfortable with. This ignores two problems: there are objective differences between styles (it is *not* all just religion), and mixing styles is thoroughly bad. At the very least, maintenance of old code should use the same style as the old code, and multi-person projects should use a consistent style throughout. >When it is time to turn a release, run all the sources through a >standard pretty-printer. Not a solution in the real world. Maybe if we had a telepathic pretty- printer, but we don't. The programmer can still do a better job of expressing his intent by doing it himself. Pretty-printers should be used as a desperate last resort to make hideous code readable, not as a routine method of cleaning up after lazy, self-centered programmers. -- SunOSish, adj: requiring | Henry Spencer at U of Toronto Zoology 32-bit bug numbers. | uunet!attcan!utzoo!henry henry@zoo.toronto.edu
jerry@starfish.Convergent.COM (Gerald Hawkins) (12/10/88)
- There are several main styles I have observed in my short experience with C: First, there is actually little disagreement on the basic idea of indenting code within a loop. How many spaces to indent seems to be purely a function of the width of your terminal or printer and the depth of nested loops. Whether or not all indents should be the same amount is never mentioned. I use TAB = 2 spaces for complex stuff and 4 spaces for simple stuff. The next major thing is where to put your '{' and '}'s. For example (pun intended): for(a = 1; a < 27; ++a) { ... ... } OR, for(a = 1; a < 27; ++a) { ... ... } Of these two, I prefer the former. It keeps all the matching pairs in the same column, where they are easy to locate. It introduces more whitespace, which makes the code look nicer and further identifies the code within the loop. The latter condenses the code slightly. If one of your objectives is "no function longer than 1 page", you may use the latter form (but I won't like it). Then there is the matter of how you handle do-while loops: do { ... ... } while (x != EOF); OR do /* while (x != EOF) */ { ... ... } while (x != EOF); OR x = 99; /* junk value so x doesn't equal EOF to start off */ while (x != EOF) { ... ... } Here, the middle version is my favorite. If the code within the while is long (25 - 75 lines) and there are lots of do and while statements, it can be confusing matching them if you use the "self-documenting" approach in the first fragment. The last fragment is crappy style, but I confess to using it when I feel lazy. I would NOT use it at work for others to read/review. BTW, the only difference between the 1st and 2nd examples is that the second example has the condition repeated in a comment prominently on the do - line. Here is a confusing one: Is it ever ok to use the form: if (a = b * 2 + 39) /* intentional assignment within condition */ ... INSTEAD OF: a = b * 2 + 39 /* more normal */ if (a) ... I say "no!" The code is unsupportable. EVERYONE who ever reads it will assume it is a trivial error (and perhaps try to correct it). There are tons more items of style I am learning for the first time, like-- If I have a code fragment which is used in only one place in one program, but it is very independent code (doesn't depend heavily on surrounding code), should I put that code into a function? If I do, it will add (trivial) execution time, (trivial) additional stack usage, and (trivial) size to the program. When do you make the decision to use #define statements? How much hard-coding is too much? When do you decide to create a library (ie, anytime a function is shared between two programs? Only when you are certain it is rock-solid? Only if it is used by many programs and will probably be used by many more? How do you decide how portable you want things to be? Rainy Days and Automatic Weapons Fire Alway Get Me Down. These opinions are mine. Jerry. (jerry@starfish.convergent.COM) -----
gwyn@smoke.BRL.MIL (Doug Gwyn ) (12/11/88)
First, let's note that style issues are partly a matter of subjective preference and partly objectively related to readability/maintainability. In article <846@starfish.Convergent.COM> jerry@starfish.Convergent.COM (Gerald Hawkins) writes: >First, there is actually little disagreement on the basic idea of >indenting code within a loop. How many spaces to indent seems to be >purely a function of the width of your terminal or printer and the depth >of nested loops. Whether or not all indents should be the same amount is >never mentioned. I use TAB = 2 spaces for complex stuff and 4 spaces for >simple stuff. I have a wonderful utility I developed at Geotronics called "retab" that remaps tabs in a single pass. It makes it possible to deal with code written according to tab conventions other than the local standard. The EMACS "filter-region" or sam "|" operations make it possible to apply this locally as needed. >The next major thing is where to put your '{' and '}'s. The way I look at it is, the {} are part of a compound statement, not part of the control syntax. (This is in fact technically accurate.) > do > { > ... > ... > } while (x != EOF); Therefore, I use do whatever while ( condition ); The style you show assumes there will be {} in the controlled statement. >Is it ever ok to use the form: > if (a = b * 2 + 39) /* intentional assignment within condition */ In code I originate (rather than patches I apply, where I try to follow the pre-existing style), I ALWAYS distinguish between Boolean and integer expressions and variables. Therefore, I would agree that the above is poor style, but have no problem with using if ( initialized = root_ptr != NULL ) I even typedef int bool so I can declare "initialized" as properly Boolean. This slight language extension seems to me so essential for robust coding that I have it in my standard header <std.h> (along with #define true 1 and #define false 0). I don't use C's implicit comparison-against-zero feature other than in the form if ( boolean ) if ( !boolean ) >If I have a code fragment which is used in only one place in one program, >but it is very independent code (doesn't depend heavily on surrounding >code), should I put that code into a function? If it performs a cleanly isolated, well-defined function, then it would be best to code it as a genuine function (unless it is in a tight loop). Otherwise, leave it in-line but set it off with block comments: /* * Now walk through the tree, * converting all unmarked nodes to * undefined name references. */ (Actually I use a different style for block comments, but the above is commonly encountered.) Don't forget that you can declare an inner block with {} and thereby restrict the scope of locally-introduced variables. This can be carried to an extreme, but it is often handy. (For instance, in the code after the above block comment, one may want a temporary register node pointer variable.) >When do you make the decision to use #define statements? #define "magic numbers", fixed limits, and other constant parameters. By using symbolic names, it is easy to globally change the values later. #define function-like or Boolean macros when an actual function would be obvious overkill: #define slave_busy (sfname != NULL && sfp == NULL) #define FreeName(name) (name==0 ? (void)0 : (free(name),(void)(name=0))) Try to avoid #ifdef system_type kind of code as much as possible. It can really cut down on readability and correctness. Often the best way to cope with system dependencies is to isolate them in separate functions provided in separate source files, with the same interface on all systems but necessarily a different implementation for each different kind of system. Then one uses whichever system interface module is appropriate at "make time", and doesn't have a bunch of conditionalized code cluttering up the rest of the sources. >How much hard-coding is too much? Almost any is too much. It is proper to use explicit constants when it is clear what they mean and that they can never need to be changed. For example, assigning 0 or 1 to initialize a counter is proper. Assuming that 03 is always the right character code for a keyboard interrupt character (i.e. ASCII ctrl-C) is not proper. >When do you decide to create a library (ie, anytime a function is shared >between two programs? Only when you are certain it is rock-solid? Only >if it is used by many programs and will probably be used by many more? There are two main kinds of library. First is a library of generally- useful programming support functions (essentially a standard C library extension). Second is a product-specific library, normally used only for large programming projects. For the first kind of library, you should put some work into defining the function interface to be as generally useful as possible, and provide a header for each package of related functions you put in the library. Also supply manual pages. For example, we have a directory /vld/include full of package headers and a corresponding library /vld/lib/libVMB.a with all sorts of useful functions, for example various random deviate generators, complex arithmetic support, spline-smoothing of data, etc. >How do you decide how portable you want things to be? If it is not a LOT of extra work to make things maximally portable, it should be done from the outset, unless you KNOW you're going to throw the code away almost immediately (e.g. it's just an experiment that cannot be patched up to make anything generally useful). You will be glad you did when you need your programs on another system unlike the one you developed them on.
peter@ficc.uu.net (Peter da Silva) (12/12/88)
In article <846@starfish.Convergent.COM>, jerry@starfish.Convergent.COM (Gerald Hawkins) writes: > Here is a confusing one: > Is it ever ok to use the form: > if (a = b * 2 + 39) /* intentional assignment within condition > */ Yes, but probably only in the common idiom: if((var = func(...)) == STATUS) { Such as: if((fp = fopen(...)) == NULL) { perror(...); return FAILURE; } or: if((nextc = getchar()) != EOF) { ... } -- Peter da Silva `-_-' Ferranti International Controls Corporation "Have you hugged U your wolf today?" uunet.uu.net!ficc!peter Disclaimer: I accept full responsibility for my typos. peter@ficc.uu.net
knudsen@ihlpl.ATT.COM (Knudsen) (12/13/88)
The new (4.0) version of Suntools includes some default editor setups for C indentation and other style conventions. Quite a few options. I was gratified to see that I could set it up for my own personal style, and in fact most of their defaults agreed with mine. So there :-) :-). (Of course, since I use Emacs exclusively, none of these settings have a thing to do with the price of beer in Milwaukee.) -- Mike Knudsen Bell Labs(AT&T) att!ihlpl!knudsen "Lawyers are like nuclear bombs and PClones. Nobody likes them, but the other guy's got one, so I better get one too."
rwl@uvacs.cs.Virginia.EDU (Ray Lubinsky) (12/13/88)
In article <6580@polyslo.CalPoly.EDU>, cquenel@polyslo.CalPoly.EDU (Chris (i = --i++;) Quenelle) writes: > In article <641@htsa.uucp> fransvo@htsa.UUCP (Frans van Otten) writes: > > > >#define then /* as white space; see below */ > > > > if (a > 10) > > then putchar('1'); > > else putchar('2'); > > Bravo!! Me Too!! > whenever the statements are blocks, I omit the then, though. > I vote strongly for this. The symmetry scans very easily for me. Hey! Why is this posted to comp.lang.c rather than comp.lang.some-language-I-invented-yesterday-cause-its-neato? Seriously, folks, having to wade through ad hoc "dialects" like this makes a C programmer's stomach churn. Source code is a medium of communication to other programmers as well as your future self when you have to maintain that code. Offbeat dialects involving fake keywords just stand in the way of comprehension. (There, I feel better :-) -- | Ray Lubinsky, UUCP: ...!uunet!virginia!uvacs!rwl | | Department of BITNET: rwl8y@virginia | | Computer Science, CSNET: rwl@cs.virginia.edu -OR- | | University of Virginia rwl%uvacs@uvaarpa.virginia.edu |
dmg@ssc-vax.UUCP (David Geary) (12/15/88)
In article <6580@polyslo.CalPoly.EDU>, cquenel@polyslo.CalPoly.EDU (Chris (i = --i++;) Quenelle) writes: > In article <641@htsa.uucp> fransvo@htsa.UUCP (Frans van Otten) writes: > > > >#define then /* as white space; see below */ > > > > if (a > 10) > > then putchar('1'); > > else putchar('2'); > > Bravo!! Me Too!! > whenever the statements are blocks, I omit the then, though. > I vote strongly for this. The symmetry scans very easily for me. ^^^^^^^^^^^^^^^^^^^^^^^^^ For you maybe, but for someone else reading your code, maybe not. One of the first things that students in my C class who are reformed ;-) Pascal programmers, want to do is this: #define BEGIN { #define END } and a whole slew of other macros to make C look like pascal. Let's say that Joe, Jim, Bob, and Phyllis are all programmers working on a C project. Joe used to program in BASIC [sic], Bob, Pascal, Jim, Fortran, and Phyllis ALGOL. So all of them spend a day or two writing macros to make their C code look like the language that their used to. Then one day, Jim needs to debug Bobs code. He's not debugging C, - he's debugging some wierd C/Pascal code, and Jim doesn't know Pascal. The moral of the story is: 1) When you write C code, you should try to make it as readable for others as for yourself. 2) If you ever have to read (or - gasp - debug) someone else's REAL C code - you're in trouble, because you don't KNOW C - you know some weird C/(insert favorite language) dialect. 3) One of the best ways to learn C is to read someone else's C code. (Even better, port it to a different machine). If you don't write "real" C, you'll have a hell of a time reading "real" C. If you want to program in C - then program in C, not psuedo-C. -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ David Geary, Boeing Aerospace, ~ ~ #define Seattle RAIN ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
apc@cbnews.ATT.COM (Alan P. Curtis) (12/17/88)
In article <846@starfish.Convergent.COM> jerry@starfish.Convergent.COM (Gerald Hawkins) writes: +- +There are several main styles I have observed in my short experience with +C: + +The next major thing is where to put your '{' and '}'s: + + for(a = 1; a < 27; ++a) + { + ... + ... + } + +OR, + for(a = 1; a < 27; ++a) { + ... + ... + } OR (my favorite): for(a = 1; a < 27; ++a) { ... ... } +Of these two, I prefer the former. I like mine because then you can say that the "right way" to right a loop is for(....) statement; where statement can be either statement; or { statements; } And life is simple again. +Then there is the matter of how you handle do-while loops: + + do + { + ... + ... + } while (x != EOF); +OR + do /* while (x != EOF) */ + { + ... + ... + } while (x != EOF); +OR + x = 99; /* junk value so x doesn't equal EOF to start off */ + while (x != EOF) + { + ... + ... + } + +Here, the middle version is my favorite. Or in my system do { ... ... } while (x != EOF); Same reasons above. I do NOT like the repeated statement comment idea, cause it is hard to maintain. If I change while condition, *I* must rember to change comment, else tis very bad. +Here is a confusing one: +Is it ever ok to use the form: + if (a = b * 2 + 39) +INSTEAD OF: + a = b * 2 + 39 /* more normal */ + if (a) + ... +I say "no!" The code is unsupportable. EVERYONE who ever reads it will >assume it is a trivial error (and perhaps try to correct it). YES! if(a = 3*b) is FINE. Well, sortof. provided you right == this way: if(3*b == a) /* notice reversedness */ Then one cannot be confused. Of course you do have to sometimes do: if( (a=b) != 0) in the simple assignment case. apc -- Alan P. Curtis | AT&T Bell Labs | apc@cblpe.ATT.COM
gwyn@smoke.BRL.MIL (Doug Gwyn ) (12/17/88)
In article <2665@cbnews.ATT.COM> apc@cbnews.ATT.COM (Alan P. Curtis) writes:
-YES! if(a = 3*b) is FINE. Well, sortof.
-provided you right == this way:
- if(3*b == a) /* notice reversedness */
-Then one cannot be confused.
Who cannot be confused??
bengsig@orcenl.uucp (Bjorn Engsig) (12/19/88)
I've used the n-key very much lately :-( -- Bjorn Engsig, ORACLE Europe \ / "Hofstadter's Law: It always takes mcvax!orcenl!bengsig@uunet.UU.NET X longer than you expect, even if you phone: +31 21 59 56 411 / \ take into account Hofstadter's Law"
nelson@sun.soe.clarkson.edu (Russ Nelson) (12/23/88)
In article <220.nlunix6@orcenl.uucp> bengsig@orcenl.uucp (Bjorn Engsig) writes:
I've used the n-key very much lately :-(
I promise I will never mention indentation again.
I promise I will never mention indentation again.
I promise I will never mention indentation again.
I promise I will never mention indentation again.
(this is *all* in response to my quest for indentation standards)
I promise I will never mention indentation again.
I promise I will never mention indentation again.
I promise I will never mention indentation again.
I promise I will never mention indentation again.
....
--
--russ (nelson@clutx [.bitnet | .clarkson.edu])
To surrender is to remain in the hands of barbarians for the rest of my life.
To fight is to leave my bones exposed in the desert waste.
jbayer@ispi.UUCP (Jonathan Bayer) (12/23/88)
In article <2417@ssc-vax.UUCP>, dmg@ssc-vax.UUCP (David Geary) writes: > In article <6580@polyslo.CalPoly.EDU>, cquenel@polyslo.CalPoly.EDU (Chris (i = --i++;) Quenelle) writes: > One of the first things that students in my C class who are reformed > ;-) Pascal programmers, want to do is this: > > #define BEGIN { > #define END } > > and a whole slew of other macros to make C look like pascal. > You must have some either very lazy or very stupid Pascal programmers in your class (no reflection on you). I too am a reformed Pascal programmer. As a matter of fact, I still program in Pascal. I also program in C. It would drive me bonkers if I had to look at my own C code which had Pascal constructs in it. It is bad enough that I still get the two languages mixed up occasionally (especially when I am working on a project which has both Pascal code and C code in it). I can not understand those programmers who try to fit one language into another. The difference between languages is what makes a language different. Changing a language to make it seem a bit more like an already-known language is akin to buying a Fererri and putting a VW engine in it because you know how to work on the VW engine. Jonathan Bayer Intelligent Software Products, Inc. -- life used to be so simple.