C++ Style Guide
When you work on a project as part of team, a coding style guide enhances code quality. When everyone uses a similar style, it is easier to understand and modify each other's code. For example, if some people use 3-byte tabs, some use 4-byte tabs, and some use 8-byte tabs, simply viewing code and determining indentation is a challenge. Use the following guide for programs in this course.
Identifiers
Identifiers should be describe the object represented by the identifier. The following conventions are used to distinguish between the kinds of identifiers within program text:
Constants
Constant identifiers should be expressed in all capital letters. Words are separated by an underscore:
const int FIELD_GOAL = 3; const double PI = 3.14159;
Variables
Variable identifiers should start with a lower case letter and use all lower case letters, with the exception that second and following words start with a capital letter (not an underscore). Document each variable for clarity.
double temperature; // temperature in degrees Farenheit int gameScore; // current score, 1-100 bool outOfRange; // true if score < 1 or score > 100
Functions
Function identifiers should start with a lower case letter and use all lower case letters, with the exception that second and following words start with a capital letter.
int cube(int x); float monthlyPayment(double interestRate, double principal); void getUserData(int aValue);
Types
Type identifiers generated using typedef, enum, struct, or class, should start with an upper case letter followed by all lower case, with the exception that second and following words also start with a capital letter. Named integer constants in enumerators follow the same rules for constants.
typedef int IntegerType; struct JellyBeanInfo; class StudentInfo; enum LightColors { RED, YELLOW, GREEN };
Comments
You can code comments using the "/*" style:
/* this is a comment */ a = b; /* another comment */ /* this is a multi-line comment */
or the "//" style:
// this is a comment a = b; // another comment // this is a // multi-line // comment
The latter method, using "//" for comments, is preferred.
Variable Declarations
An end-of-line comment should be used for every variable to describe the purpose/usage of the variable.
int i; // loop counter int sumOfScores; // sum of all test scores read from file struct Term { // one term of a polynomial Term *next; // pointer to next term int exp; // exponent int coef; // coefficient };
Code Blocks
Comments add clarity to a program. If the code is self-explanatory, then group the code in blocks and add a short comment before each block to summarize the action taken. Typically, this is all that is needed. If additional explanation is required to explain non-obvious code, include a longer comment block. In one case I had 30 lines of comments describing the action taken by 3 lines of code. Comments for code blocks should be indented the same as the underlying code.
// remove curr node curr->prev->next = curr->next; curr->next->prev = curr->prev; // add curr node to head of list curr->next = head->next; curr->prev = &head; curr->next->prev = curr; curr->prev->next = curr;
Function headers
A function can be visualized as a logical block of code that does a task. A function may have inputs, outputs, and a return value. This suggests the following commenting style:
int divide(double dividend, double divisor, double *quotient) { // inputs: // dividend numerator of expression // divisor denominator of expression // outputs: // quotient numerator / denominator // returns: // 0 all okay // 1 divide by zero // action: // divide numerator by denominator and output quotient if (divisor == 0) return 1; *quotient = dividend / divisor; return 0; }
You can also use preconditions and postconditions as suggested by your text. Either way, the user should be able to understand what the function does by reading the comments.
For large programs that have function prototypes in an include file, be sure to document the interface in the include file. Otherwise, the user will have to delve into your implementation file to determine how to call the function. You are not required to include the same documentation in the implementation file. Some programmers do this since it's convenient to find. Others prefer to omit this documentation as it's available in the include file, and any changes to the interface require changing documentation in two places.
Statements
Leave one space before and after operators. For example, do this:
if (a > b + 5) cout << a << endl;
and not this:
if (a>b+5) cout<<a<<endl;
This is not a hard-fast rule. For example, you may want to indicate precedence with spacing:
x = a + b*c;
Other exceptions to this rule include dereferencing and scope resolution operators:
*x = *y; a->value = b->value; std::cout << x << std::endl;
All code within brackets should be indented one level. Indent consistently by 4 spaces. For the if statement two styles are popular:
// method-1 // method-2 if (a > 5) { if (a > 5) x = a; { y = b; x = a; } else { y = b; x = b; } y = a; else } { x = b; y = a; }
Method 1 is shorter and more likely to be visible without scrolling. Proponents of method 2 appreciate the fact that you can easily match braces. Choose the method you like best and stick with it. For functions you'll find two styles:
// method-1 // method-2 int main() { int main() return 0; { } return 0; }
You'll find folks that use method-1 for code and method-2 for functions. In fact, this is the style used by the majority of programmers. Choose your style, or mixture of styles, and be consistent. Here's how to indent the switch statement using method-1. Note that the case statement is actually a label and should be outdented.
switch(x) { case 'a': y = 5; break; case 'b': y = 6; break; }