After the first few labs, graders will assign minor penalties for poor commenting and coding style. Here are some style tips for good C++ style:
- You should pick meaningful variable names.
// good
int *array = new int[size];
// bad
int *a = new int[size];
- You should use correct and consistent indentation. Lines of
code within a block should be indented two spaces further than lines
surrounding them.*
//good
if(condition) {
cout << "Test" << endl;
}
//bad
if(condition) {
cout << "Test" << endl;
}
*if your text editor's default indenting is four spaces instead of two, don't stress about it. Just be consistent when indenting.
-
You should use a code block whenever possible, even if it's not
necessary. This will help you avoid subtle/messy errors in the
future.
//good
if(condition) {
cout << "Something" << endl;
}
//legal but bad
if(condition)
cout << "Something" << endl;
- Do write comments at the top of each file, indicating your name and the purpose of the code file
- You don't have to write a comment for each line of code, but do write comments about meaningful chunks of code such as a loop, if/else statement, etc.
- Do write comments describing the purpose and signature of each
function declaration. Use @param to describe an input
parameter, @return to describe what gets returned, and
@throws to describe exceptions that should be thrown. An example
lies below:
/**
* Retrieves the first element of the list.
* @return The element at index 0 of this list.
* @throws runtime_error If the list is empty.
*/
virtual T peekHead() = 0;