- Always include your name and assignment information
as comments.
// Allan Kochis
// Assignment 1.
// Page 745 # 23
- set the line width to 78 and break long lines before an operator.
// long line
cout << "C++ Coding rules" << endl << "Failure to follow these rules" << endl << " will result in loss of grade points " endl;
// preferred style
cout << "C++ Coding rules" << endl
<< "Failure to follow these rules" << endl
<< " will result in loss of grade points " endl;
- Use meaningful names. One character names are unacceptable.
use camel back for longer names.
Use of Hungarian notoation is optional.
// unacceptable
p=o*(1-d);
// Better
Price=originalPrice * ( 1 - salesDiscount );
// Hungarian
fPrice=fOriginalPrice * ( 1 - fSalesDiscount);
- Use whitespace on binary operators to make them stand out.
// Compacted
Price=originalPrice*(1-salesDiscount);
// Readable
Price=originalPrice * (1 - salesDiscount);
- Parenthesize in either K&R or Classic style.
K&R style.
while(count < 10) {
cout << count << endl;
count++;
}
Classic style
while(count < 10)
{
cout << count << endl;
count++;
}
- Don't mix your parentheses style.
Use either K&R or classic style not both.
Except for functions. Always use classic for
the function body
int Area(int iLength, int iWidth)
{
// Compute the area of a rectangle
// Input lenght and width
// Returns area
int iArea;
iArea=iLength*iWidth;
return iArea;
}
- Use indents of four spaces, do not use tabs.
Indent each subordinate block of code.
if(iYear%4 == 0) {
if(iYear%100 != 0) {
bLeap=true;
}
else {
if(iYear%400 == 0) {
bLeap=true;
}
else {
bLeap=false;
}
}
}
else {
bLeap=false;
}
- Don't cuddle else statements. else statement should line up with
the associated if statement
// cuddled esle
if(iCount > 100 ) {
bBonus=true;
} else {
bBonus=false;
}
// uncuddled else
if(iCount > 100 ) {
bBonus=true;
}
else {
bBonus=false;
}
- Never place two statements on a line.
iCount=1; bControl=true;
iCount=1;
bControl=true;
- The C++ compiler will accept almost any style of code.
While the following ugly code is valid syntax, it will compile and run,
do not use this style.
Please strive to make your code human readable.
#include <iostream>
using namespace std;int main(){float E;int C=0;E=1.0;cout
<<"Computing machine Eilon "<<endl;while(1.0+E>1.0){C++;E/=2;}E*=2;cout<<
"It took "<<C<<" iterations to compute Epsilon = "<<E<<endl;system("pause");return 0;}