In many circumstances whitespace is not required in order for compilers to correctly compile source code, even though the result is unreadable to us. There are three major ways we use whitespace to format code for maximum clarity:
Bad Formatting
|
Good Formatting
|
| Good | y = 2*y + x/y + 5; |
| Bad | y=2*y+x/y+5; |
Comments should be indented consistently with the block of code they
describe. Comments can be divided into two general categories,
strategic and tactical.
|
/***************************************************
Filename: f2c.cpp
Author: MIDN Nobody Smith (259999)
Fahrenheit to Celsius Conversion
***************************************************/
#include <iostream>
using namespace std;
int main()
{
// Read temperature in Fahrenheit
double Tf;
cout << "Enter temperature in Fahrenheit: ";
cin >> Tf;
// Compute temperature in Celsius
double Tc;
Tc = (Tf - 32)*(5/9.0); // .0 forces division as double
// Write temperature in Celsius
cout << "That is " << Tc << " degrees Celsius."
<< endl;
return 0;
}
|
yardsPerCarry
rather than just x for program readability. This must be balanced against
using names which are too long. (Fifteen
or so characters approaches the "too long" limit.)
| Good | Good | Bad | Bad |
|
|
| |
const int PI = 3.14;It's generally good to avoid lower case letter 'L', or the letter 'O' in names unless they are part of normal words. This is to avoid confusion with the numbers 1 and 0. For example, is "
cell" c- e -
1- ONE or c- e- 1-1?
There are some benefits to this approach:
As one more example, the online notes sometimes explain technical details. In this case, reading one paragraph may take even 5 minutes or more to work out all the details in your brain. Don't skip through the details. The devil is in the details.