(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 {...};
- Consider prefixing or suffixing certain identifiers to emphasize
some special nature:
int gGlobalVariable;int *pPointerToInt;ORint pointerToIntPtr;
- Statements
- Don't put multiple statements on a single line.
- If the body of a
whileorforis empty, place the terminating semicolon on a separate line, to indicate that this is intentional.while ( cin.get() != '\n' ) ; - Place the
whilepart ofdo-whilestatements 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.
- to indicate nesting of control structures (
- 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