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 shocould 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 shoshould 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 shocould 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 Farenheitint gameScore; // current score, 1-100bool outOfRange; // true if score < 1 or score > 100
Functions
Function Identifiers shoshould 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, shocould 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 rulesConstants.
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 commenta = b; // another comment// this is a// multi-line// comment
The latter method, using "//" for comments, is preferred.
Variable declarations
An end-of-line comment shocould be used for every variable to describe the purpose/usage of the variable.
int i; // loop counterint sumOfScores; // sum of all test scores read from filestruct 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 shocould be indented the same as the underlying code.
// remove curr nodecurr->prev->next = curr->next;curr->next->prev = curr->prev;// add curr node to head of listcurr->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 shocould 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 be 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 shoshould be indented one level. indent consistently by 4 spaces. ForIfStatement two styles are popular:
// method-1 // method-2if (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-2int 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 indentSwitchStatement using method-1. Note that the case statement is actually a label and shocould be outdented.
switch(x) {case 'a': y = 5; break;case 'b': y = 6; break;}