Some of these issues are purely religious, i.e., personal preference. Whichever style you use, the key is consistency! Pick your own style and stick with it!
if (test == 1) // preferred style
{
...
}
if (test == 1) { // K & R style
...
}
if (test == 1) // GNU style
{
...
}
You must use braces for all block structures (if/else, do/while, while, for) even if the block contains only one statement! The key here is maintainability. With a few keystrokes (i.e., adding the left brace and the right brace), you can later add as many statements as you wish to the block.
Use meaningful, i.e., self-documenting variable names.
int i; // loop counter: sometimes simple variable names are acceptable double squareroot; // all lower case double square_root; // underscore adds readability double squareRoot; // compound word convention double SquareRoot; // capitalized compound word convention double SQUAREROOT; // Wrong! use all capitals for constants only! // For example, const double PI = 3.14159265; // constant const int N_TEAMS = 6; // underscore adds readability
Comment block at top of program // Program: sqroot.c // Description: This program calculates the square root for a // number that the user enters. // Author: Mike Boldin // Date: 1999.01.12 date of last modification Includes #include... Function declarations/prototypes double squareRoot(double); ... Comment block for each function // Function: main // Description: Program entry point. // Parameters: None. // Returns: 0 // Notes: None. use return-type function name(args ...) or return-type function-name(args...) int main() in C, use int main(void) { comment for each variable double number; // number that the user enters cout << "Enter a positive real number: "; cin >> number; double root; // square root of number root = squareRoot(number); cout << endl << "The square root of " << number << " is " << root << endl; // main() declared to return an int; I must return an int! return 0; } // end of main // Function: squareRoot // Description: calculate the square root of a real number // Parameters: number, the number for which to calculate the square root // Returns: the square root of number // Notes: number must be >= 0 double squareRoot(double number) { double root; // square root (returned) if (number >= 0.0) { root = ... } // end if else // negative number { cerr << "squareRoot: bad argument" << endl; } // end else return root; } // end of squareRoot ... more functions here // end of sqroot.c