1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

Indentation

From cpwiki

Jump to: navigation, search

Indentation refers to the spacing that occurs before a line begins in a source file, and is one part of an umbrella term, programming style: the personal or sometimes professional preferences of programmers (such as the habits of hobbyist programmers, or style guidelines used in the workplace) which make programming instructions more presentable or legible.

Our web site has no formal style guidelines; however, from a presentability and legibility standpoint, it is easier to maintain and read code that is carefully indented. At our site, we strongly encourage people to adopt some indentation standards for themselves so that they find using the message boards a more helpful and fleeting experience and are more prepared to work on projects with others.


Contents

Indentation as a Model of Consistency

As in writing, one style does not suit all the programmers in the world. Apart from expectations in the workspace, programmers will commonly differ on several points concerning indentation and programming style, mostly out of personal preference.

Most view indentation as a presentation model that simply needs consistency and consideration for the medium where the code will be printed or displayed. For instance, at cboard, we often see code indented with a mixture of tabs and spaces instead of picking one or the other and unintentionally causing it to be formatted improperly by browsers in a fixed-width font.

Achieving consistency is easy if you choose to adopt an already existing style such as K&R or Allman style, however, programmers sometimes develop their own tastes and opinions about what “looks good” through programming experience. Common considerations in the format of any style guideline are:

  • placement of braces and parentheses;
  • spacing between operators;
  • tab length (or the sum of the spaces from the beginning of a line);
  • the arrangement and format of comment lines;


Individuals may find it rewarding to rotate their indentation styles to keep their work from getting repetitive or simply getting used to a style they may be expected to use more commonly. It is equally important to avoid deviating from the style, and to never rotate styles in the middle of a source file or project, where the indentation may become a distraction.

Placement of Braces and Parentheses

Some languages, such has Python or Haskell, rely on whitespace expressly to delimit their statement blocks ("forced indentation"), but most languages do not use indentation this way. In C, C++, and C# the curly braces are used by the compiler to delimit the beginning and the end of functions and other statement blocks, such as if or while. Formatting your braces consistently is generally only an aid to human readers: most will agree good style is any format which allows a programmer with working knowledge "eyeball" statements associated with those constructs.

If you have a standard to adhere to, formatting rules for this are usually defined in the sections that explain how to write compound statements and function declarations. There are many ways to format your braces and parentheses, but be consistent with what you choose. Let's pretend that person B just finished fixing case V in person A's C-like code:


switch (example expression)
    {
    case T:
        {
        result = foo();
        more work;
        print(result);
        break;
        }
    case U:
        {
        different work;
        print(bar(work));
        break;
        }
     case V:
        {
        complex work;
        result = quz(complex work);
        quux(result);
        break;
        }
    }

Person B did a fine job in formatting because they edited in Whitesmith style like the person before them.

Spacing Between Operators

As written in this version of the Indian Hill Style Guide, expectations are not high: most if not all styles will let programmers use whitespace generously. Attention to how you space out your loops and other complex calculations, including where you break your lines, are all efforts well appreciated by your peers because they may have to maintain your work in the future.

Tab Length

The default tab length for most text editors (such as notepad, vim or TextPad) is eight; that is, there is a real tab character written to the source file. Most editors support replacing tabs with a set number of spaces, which is a feature that helps maintain formatting portability in source code.

Format of Comment Lines

The most important part of a comment is what it says and not what it looks like, and this sentiment is often reflected in more formal style guides. Still, it shouldn't imply that you aren't allowed to make some effort to distinguish the purposes of the comments if you don't have a standard to follow. For instance:

/* $ This is a block comment which explains foo().
* $ The idea here is a consistant, readable format for comments which
* $ discuss the preconditions of foo(), it's parameters, and 
* $ what it returns. It is also very seachable in large source files:
* $ any global search for, say, "\* \$" should include this comment in the 
* $ results.
*/
int foo( void )
{
   work;
   work; /**FIXME: something's broken here**/
   work;
   return a = (b != 0) ? bar(b) : bar(c);
}

While the purpose of block or FIXME comments and the draconian way to arrange them would be beyond the scope of this article, the example demonstrates that simple systems are often more useful than adopting no standards and more helpful than simply writing no comments at all. Focusing more on what comments look like than what they say often wastes your time without marginal benefit.

Examples of Poor and Proper Indentation

Notice the lack of consistency in this broken swatch of code's spacing, and the poor attention to the bulleted list in the consistency section of the article, here.

(C):

float m, k, g, x[], v[], time_increment,time[], w2, w, p, f[], A, omega;


 fprintf(output, "%f %f\n", g, w);
   
time[0]=0;
 i=-1;
  
  while((time[i]>=0)&&(time[i] < p))
  {
 
   if(CASE_FLAG==1)
   {
    f[i]=0;
   }
   else if(CASE_FLAG==2)
   {
    f[i]=A*cos(omega*time[i]);
   }
   
    i++;
    
    time[i] = i*time_increment;
    v[i+1] = v[i] - (g*v[i] + w2*x[i])*time_increment + (1/m)*f[i]*time_increment;
	x[i+1] = x[i] + v[i+1]*time_increment;
  
	fprintf(output, "%f %f\n", time[i], x[i]);
  }
  	
	fclose(output);

Here is a more carefully typed version of the broken code. Again, note the consistency in indentation level, brace placement, and spacing.

float m, k, g;
float x[], v[];
float time_increment;
float time[];
float w2, w, p;
float f[];
float A;
float omega;


fprintf(output, "%f %f\n", g, w);   
time[0] = 0;
i = -1;

while((time[i] >= 0) && (time[i] < p))
{
    if(CASE_FLAG == 1)
    {
        f[i]=0;
    }
    else if(CASE_FLAG == 2)
    {
        f[i] = A * cos(omega * time[i]);
    }
   
    i++;
    
    time[i] = i * time_increment;
    v[i+1] = v[i] - (g * v[i] + w2 * x[i]) * time_increment + (1/m) * f[i] * time_increment;
    x[i+1] = x[i] + v[i+1] * time_increment;
  
    fprintf(output, "%f %f\n", time[i], x[i]);
}

fclose(output);

Tabs versus Spaces

When indenting, we use either tabs or spaces. Since there are people in both groups who endorse their use, there's no easy answer to what you should use[1]. The answer to this question becomes: use whatever you think is best, but be consistent.

When "smart indenting" is turned off, it creates a potential problem for the plain text source file when it is used by a different program such as another editor or a web browser. Consider a source file which looks like this in a fancy editor:

    if (search && source) {
        while (*search && *source) {
            if (*search == '\\') {       /**match escaped star**/
                ++search;
                match = *search == '*' && *search == *source;

In a simple, plain text editor, if the same code looks like this:

    if (search && source) {
		while (*search && *source) {
			if (*search == '\\') {       /**match escaped star**/
                ++search;
                match = *search == '*' && *search == *source;

it is clear that the programmer failed to rely on editor features but continued to indent as if they were there. A bad thing, since the result is no consistency, and in effect, no indentation. This is an important reality for thread posters on cboard to face, because they will be frequently pasting their code around outside of their friendly editor.

On a few remaining editors the tab key cannot create space-character indentation. On these editors, it is a good suggestion to avoid indentation based on space characters. On any other editors where the user has an option to choose whether the tab key creates space characters or tab characters, one should use what they feel most comfortable with. It will at least provide consistent plain text.

References/See Also

Personal tools