User Tools

Site Tools


guides:programstyle:indentation

Indentation

The goal of indentation is to make it easier for programmers to recognize blocks of code contained within a structure. To that end, code within a structure should be indented by a standard amount. A second use of indentation is to associate code from a single statement which exceeds a single line with the beginning of that statement.

Code in a Code Block

Code inside of a code block,enclosed in {}, or that constitutes the body of a control structure should be indented. This allows programmers reading the code to instantly identify the body of these control structures.

Example of acceptable use:

int value;
 
int max, 
    min;
 
int count = 0;
 
cin >> value;
max = value;
min = value;
 
while (cin) {
   if (max < value) {
      max = value;
   }
 
   if (min > value) {
      min = value;
   }
 
   count++;
   cin >> value;
}

Code should be indented by a standard amount. In general one space is too little to allow easy visual identification of the control structure. You should not use tabs for indentation. If you wish to use tabs, or your editor auto indents with tabs, you should replace tabs with spaces.

Unacceptable Example:

int value;
 
int max, 
min;
 
int count = 0;
 
cin >> value;
    max = value;
 min = value;
 
while (cin) {
if (max < value) {
max = value;
}
 
             if (min > value) {
      min = value;
      }
 
   count++;
           cin >> value;
                       }

A single statement occupying multiple lines

A second use of indentation is to highlight a line of code which wraps past the maximum line limit. This frequently occurs in parameter lists, output statements and variable declarations. Indentation gives programmers a visual clue that the line has been wrapped.

In a long parameter list, break the line at the beginning of a parameter declaration and align the next parameter declaration with the first declaration on the line above it.

void FloodFill(int & worldArray[MAX_ROWS][MAX_COLUMNS], int rowSize, 
               int colSize, int fillColor, int backgroundColor,
               int currentRow, int current column);

When declaring multiple variables of a single type it is helpful to indent each new identifier, especially when variables are initialized in the same statement.

    int rowSize = 10,
        colSize = 20,
        fillColor = 4,
        backgroundColor = 7;
guides/programstyle/indentation.txt · Last modified: 2022/08/02 11:59 by 127.0.0.1