4 Bears Online

Comics | Jokes about India | Men and Women Jokes | Funny articles and essays | Only in America | More serious Articles and Essays |
Articles/News   | Readings   | Humor   | Travel/Hiking   | More/Informational Links  

Notes on Programming Style

(c) 1995 andrew thomas-cramer
This document may be folded, spindled, or mutilated as desired, as long as the copyright notice and this restriction remain untouched.

[From the UNIVERSITY OF WISCONSIN-MADISON's Data-Structures Course (CS367) Homepage.]

You should use a consistent style in your programs, one which enhances their readibility. Below are some suggestions. You're welcome to choose another style, as long as your code is at least as readable as it would be if you followed the suggestions below.

Naming
  • Name identifiers meaningfully. A few single-letter identifiers have accepted uses: i,j, and k for loop indices, c for a character, s for a string.
  • Use a consistent naming scheme for identifiers. For example:
    • int variableName;
    • const int constantName;
    • enum EnumType { constVal, anotherConstVal, yetAnotherConstVal };
    • void FunctionName() {...}
    • class ClassName {...};
    (C programmers sometimes put constant names in all-uppercase. This was a standard style in C because constants were implemented as macros, which were put in all-uppercase mostly because they were flaky.)

  • Consider prefixing or suffixing certain identifiers to emphasize some special nature:
    • int gGlobalVariable;
    • int *pPointerToInt; OR int pointerToIntPtr;
Statements
  • Don't put multiple statements on a single line.
  • If the body of a while or for is empty, place the terminating semicolon on a separate line, to indicate that this is intentional. while ( cin.get() != '\n' ) ;
  • Place the while part of do-while statements on the same line as the closing brace, to emphasize its dependence to the statements above. (Placing it elsewhere can make it look independent, making the code less readable.) do { statements } while ( condition );
  • Consider commenting the closing brace of larger control structures. For example: for ( i = 0; i < max; i++ ) { if ( apples == oranges ) { ... many lines of statements ... } /* if ( apples == oranges ) */ } /* for (i...) */
White space
  • Use indentation:
    • to indicate nesting of control structures (if, while, for, switch) -- e.g.: for ( ) { for ( ) for ( ) for ( ) { stmts { { BUT NOT stmts } stmts stmts } } }
    • to organize parts of expressions.

  • Use blank lines to organize code. For example: void function1( ) { int decl1; stmtA; stmtB; stmt1; stmt2; } int function2( ) { ...

Jan. 18, 1995 Andy Thomas-Cramer andrewt@cs.wisc.edu

http://www.4bearsonline.com/collections/cs/index.shtml