Oh NO! It's the dreaded style lecture!

The following are some guidelines to use in writing your programs. They're fairly standard - as you read more code you'll see that many people use them. Learn 'em, live 'em, love 'em. Otherwise other people won't be able to read your code. (Or worse yet , they'll make fun of you.)

White space is your friend. Use blank lines to separate logically separate parts of a function. Use a blank space around every binary operator.

	x1 = (-b - sqrt(b * b - 4 * a * c)) / (2 * a) ;     /* Good */

	x1=(-b-sqrt(b*b-4*a*c)/(2*a);     /* Bad programmer, no Jolt.*/
Leave a blank space after (and not before) each comma, semicolon and keyword, but not after a function name.

Indent! Indent code that is part of any of the following blocks: if/else statement, switch statement, any loop. Also indent function definitions, struct declarations and class definitions.

Some people say to indent by 3 spaces, some say 4. I haven't been able to figure out how to change the tab stop in pico, so for our purposes, using the tab is fine. (If you're using another editor like vi or emacs you can set your tab to 3 or 4.)

Be consistent in your indentation.

Parameters must have meaningful names unless the function is very general (like our printnc() function).

Variables. Don't define them at the beginning of a block. Define each variable just before it is used for the first time. Initialize every variable when you define it, unless its value will be set in the next line of code.

Like:

	int i = 0;
or:
	int size;
	cin >> size;
Variable names should be lowercase. Constant names should be uppercase.

Every Function must have a header comment that (at least) describes what it does, what its parameters are and what its return value is (if any).

Make your functions 30 lines of code or less. If a function is longer than that it can probably be split into smaller functions. (This total does not include comments, blank lines or lines that contain only braces. Functions that consist of a long if/else or switch statement are exempt.)

Don't use Magic Numbers. A magic number is an integer constant embedded in your code. They are evil. Define a constant and use that instead.

Don't do this:

	while(size > 60)
	{
		cout << "Please enter an integer less than 60: " << endl;
		cin >> size;
	}

Do this:
const int MAX_ROW = 60;

	...

	while( size > MAX_ROW)
	{
		cout << "Please enter an integer less than " << MAX_ROW << endl;
		cin >> size;
	}

Now if MAX_ROW changes you only have to change it in one place, not throughout your program. And to someone else looking at your code MAX_ROW is much more meaningful than 60.


Some of the guidelines here were taken from "Computing Concepts with C++ Essentials" by Cay S. Horstman, published by John Wiley & Sons. They are copyright 1997, by John Wiley & Sons. All rights reserved.
Updated: October 5, 1998

khanna@nimbus