This is the main component of the coding standard that is specific to CSE 232. Follow the conventions in the course pack examples, which use 6 fields:
"Purpose" can be omitted if the name of the function, combined with the other fields, make it completely obvious what the function does. The other fields can be omitted only if you would have written "None" as the value.
For class constructors and destructors, you can replace the "name" of the
function (which is the same as the class name) with "default constructor",
"value constructor", "copy constructor", or "destructor".
The "Purpose" field should fully explain everything another programmer needs to know in order to use your function, except information that would be redundant with the other fields. For very short functions, you may not need any additional comments in the function body if your "Purpose" description is thorough. For most functions, you will need inline comments (right before the relevant code) with implementation details (see below).
In the "Receive" field, don't just give the types of each parameter, give the name and purpose of each. The "Return" field should include values returned through reference parameters, as well as normal return values.
The "Input" and "Output" fields should be used only for terminal and file
I/O, not for parameters or return values.
In a nutshell, use meaningful names. Single letter variable names are
never acceptable except for indices and iterators, which are commonly
named 'i', 'j', and 'k'.
Bad |
Good |
A, B, C |
sideA, sideB, sideC |
H, W |
height, width |
Abbreviations, on the other hand, are fine (ex. "stackPtr" = "stack
pointer").
Do not use the name "temp" except for variables that really are used for temporary storage of a value and nothing else, such as in the swap algorithm.
/* Ex. Swap Algorithm */
int x, y;
...
// swap x and y
int temp;
temp = x;
x = y;
y = temp;
If you find yourself calling things "temp1", "temp2", etc., then you
definitely need better names.
The most important thing here is to be consistent. However, there are
some common conventions for C++:
Name Category |
Example |
Alternate Style |
Variables and functions: | someVariable, someFunction | some_variable, some_function |
Classes, structs, enumerations |
ClassName, StructName, EnumName |
|
Constants |
SOME_CONSTANT |
Note that arrays and objects count as variables.
If you follow these conventions, you will be able to use names like this:
/* Ex. Class and Variable Names */
class Student {...};
...
const int NUM_STUDENTS = 20;
Student students[NUM_STUDENTS]; //array of students
...
for (int i = 0; i < NUM_STUDENTS; i++) {
Student student; // temp student for input
cin >> student;
students[i] = student;
}
Use 2 or 4 spaces per level of indentation, or hard tabs.
Do not mix spaces with real tabs -- the indentation will be ruined when
others with different tab settings try to view your code, print it to the
terminal, etc. If you use multiple editors, configure them to do the same
thing so this doesn't happen.
See Vim Configuration for auto-indentation in Vim. For other editors, look at the settings/options.
When a single expression won't fit in a single line, you can extend it to the next line. Increase the indentation when you do so.
x = the + sum + of + an + extremely
+ long + expression + that +
extends
+ over + multiple + lines;
In general, you should avoid splitting a single calculation into multiple
steps, especially if the entire calculation will fit on one line. However,
it might make sense to do so if the results are those intermediate steps
are also used elsewhere, or the code will be clearer that way, such as
when each sub-calculation represents a meaningful value.
Basically, use space to improve readability. Add space between operators
and operands, commas, and semicolons, and colons. Add space on the outside
of parentheses and brackets (though see an exception below).
Examples from http://geosoft.no/development/cppstyle.html
a = (b + c) * d; // NOT: a=(b+c)*d
while (true) { // NOT: while(true){
...
doSomething(a, b, c, d); // NOT: doSomething(a,b,c,d);
case 100 : // NOT: case 100:
for (i = 0; i < 10; i++) { // NOT: for(i=0;i<10;i++){
...
The main exception is with parentheses around while/for conditions and
function parameters, where you can have space inside the parentheses, or
no space at all, as long as you are consistent.
f(x, y, z);
// no space around parentheses
f( x, y, z ); // space inside parentheses
f (x, y, z)
; // space outside parentheses
In compound arithmetic expressions, you will sometimes get the best results by omitting spaces in around *, /, and % when you have several terms being added or subtracted. This is preferable to adding parentheses that do not change order of operations.
Ex. a = b*c + d/e - f%g // NOT:
a = (b * c) + (d / e) - (f % g)
In Boolean expressions, however, you should add parentheses around sub-expressions.
Ex. if ((x + 2*y > z) || (p < q))
Each pair of parentheses will then contain at most one comparative operator.
Add one blank line between each logical block of code.
Example from http://geosoft.no/development/cppstyle.html
Matrix4x4 matrix = new Matrix4x4();
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
matrix.setElement(1, 1, cosAngle);
matrix.setElement(1, 2, sinAngle);
matrix.setElement(2, 1, -sinAngle);
matrix.setElement(2, 2, cosAngle);
multiply(matrix);
Add at least one blank line (preferably two) between functions and other file components.
However, don't ever double space your code. This is just as useless as no spacing, and just creates the need for more scrolling./* Ex. Function Spacing */
using namespace std;
#include <header1>
#include "header2"
const int CONST_1 = 100;
const int CONST_2 = 200;
const int CONST_3 = 300;
/*
* function1 header
*/
void function1() {
...
}
/*
* function2 header
*/
int function2(int param1, int param2) {
...
}
Describe the purpose of every variable, with units if applicable, unless
it is absolutely obvious from the name and type alone what the variable is
for. Align the comments as much as possible.
int var1; // describe
int var2; // describe
double var3; // describe
double var4; // describe
// do X
...
...
// do Y
...
...
In some case, you may be able to get away with just one comment for a couple blocks.
// do X
...
...
...
...
If you need multiple lines for a comment, start each with another //.
Don't let your comments go past 80 characters per line.
// some really ..........
// long comment ..........
Use off-side comments very sparingly (other than in variable declarations). Inline comments should almost always precede the code they describe.
If-else statements are a little tricky, but most of the time a block comment will do the job.
if (X) {
// do Y
...
}
else {
//do Z
...
}
See below for more on logic formatting.
Add additional comments whenever what you're doing is not obvious. However, do NOT just translate the syntax.
Instead, make sure it's clear WHY you are doing what you're doing. Only omit comments when what you are doing is completely self-evident, such as in a short function with a good "purpose" field in its header./* BAD Examples */
Thing thing = new Thing(); // make a new Thing
X += Y; // add Y to X
if (X > Z) { // if x is greater than z
...
}
Long FunctionsBreak long chunks of code into sections with mini-headers.
int longFunction() {
// init variables
...
//
// Section 1
//
// Block A
...
...
// Block B
...
...
.
.
.
//
// Section 2
//
// Block C
...
...
.
.
.
}
For if-else, you generally have two choices for comments:
// Describe the purpose of the whole
if-else
if (cond)
{
SHORT BLOCK
}
else
{
SHORT BLOCK
}
// Optional:
purpose
of the whole if-else
if (cond)
{
// do X
MEDIUM BLOCK
}
else {
// do Y
MEDIUM BLOCK
}
As with sequential logic, your comment for an if-else or switch-case block could be the purpose of the code, or an explanation of what it means, such as the name of a formula or the English wording of a calculation. When they are long, you will probably need more than one comment per block.
If you choose to use bracket-less if-else (only possible when each block is only one statement), the same rules apply.
// Optional:
purpose
of
the whole if-else
if (cond)
// do X
ONE STATEMENT
else
// do Y
ONE STATEMENT
Switch case also works the same way. If the cases are long, you should
add space between them, since brackets around case bodies are optional
(except when you declare variables within a case).
// Optional: purpose of
entire
switch-case
switch (var) {
case 1:
// do X
...
break;
case 2:
// do Y
...
break;
default:
// do Z
...
break;
}
C++ has a somewhat strange syntax for I/O, but it actually works pretty well.
In general, you can include multiple output items in a single "cout"
statement. Put spaces around << and >>, just like any other
operator.
cout << "The roots are: " << A << ", " << B << ", and " << C << endl;
You can also extend a single "cout" statement over multiple lines. Do
this whenever a single line of output takes more than one line of code to
generate, or when you output several lines one after another. When you do
this, increase the indentation all lines after the first.
cout << "\nStatistics for this sample:" << endl
<< " Maximum: " << max << endl
<< " Minimum: " << min << endl
<< " Mean: " << mean << endl
<< " Median: " << median << endl << endl;
You can also make the output easier to visualize by giving empty lines in the output their own line in the code.
cout << endl
<< "Statistics for this sample:" << endl
<< " Maximum: " << max << endl
<< " Minimum: " << min << endl
<< " Mean: " << mean << endl
<< " Median: " << median << endl
<< endl;
It's usually safe (but potentially confusing) if you embed actual
calculations in output code, but there are some cases where you will need
to calculate the results beforehand, store them in variables, and embed
the stored results in the output code.
Note that if you do use embedded calculations, it's particularly
important to use "endl" at the end of each line, rather that the newline
character ('\n'). If you don't and your program crashes or hangs during
any calculation embedded in the output code, nothing will be output, so
you won't be able to tell which calculation failed.