3.5 Indentation and Code Format

I l @ ve RuBoard

To make programs easier to understand, most programmers indent their programs. The general rule for a C++ program is to indent one level for each new block or conditional. In Example 3-1 there are three levels of logic, each with its own indentation level. The while statement is outermost. The statements inside the while are at the next level. The statement inside the if ( break ) is at the innermost level.

There are two styles of indentation, and a vast religious war is being waged in the programming community as to which is better. The first is the short form:

 while (! done) {      std::cout << "Processing\n";      next_entry(  );  }  if (total <= 0) {      std::cout << "You owe nothing\n";      total = 0;  } else {      std::cout << "You owe " << total << " dollars\n";      all_totals = all_totals + total;  } 

In this case, most of the curly braces are put on the same line as the statements. The other style puts the curly braces on lines by themselves :

 while (! done) {      std::cout << "Processing\n";      next_entry(  );  }  if (total <= 0) {      std::cout << "You owe nothing\n";      total = 0;  } else {      std::cout << "You owe " << total << " dollars\n";      all_totals = all_totals + total;  } 

Both formats are commonly used. You should use the format you feel most comfortable with. This book uses the short form. (It saves paper.)

The amount of indentation is left to the programmer. Two, four, and eight spaces are common. Studies have shown that a four-space indent makes the most readable code. You can choose any indent size as long as you are consistent.

Automatic Indenting

The vim editor is a vi -like program with many additional features. This includes the ability to automatically indent C++ programs. To turn on automatic four-space indentation, execute the commands:

 :set cindent :set sw=4 
I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net