Indentation

Block statements such as loops and conditionals should have the sub statements indented. This easily shows the program intent to the reader. The number of spaces to indent is less important than the indentation itself. Most programmers agree that 2 to 4 spaces are sufficient for readability. The most important thing is to be consistent with your spacing. Likewise, the placement of the starting curly brace isn't important, (although you can find some interesting arguments online), but it is important to consistently place it in the same location:

//This shows the purpose of the statement 
if (s_isFullScreen)
{
s_style = FULLSCREEN_STYLE;
SetFullScreen(true);
}

//So does this
if (s_isFullScreen) {
s_style = FULLSCREEN_STYLE;
SetFullScreen(true);
}


//This does not shows the intent of the statement
if (s_isFullScreen)
{
s_style = FULLSCREEN_STYLE;
SetFullScreen(true);
}

It is important to remember that in C++, indentation has no meaning to the compiler. Without the curly braces, loops and conditionals will execute only one statement. For this reason, some programmers will always use the curly braces, regardless of how many sub statements are needed:

/*Single statement in the loop*/ 
while (i++ < 10)
printf("The value of i is %d ", i);


/*After adding another statement*/
while (i++ < 10)
printf("The value of i is %d ", i);
printf("i squared is %d ", i*i);

The preceding example is misleading, because only the first statement will be part of the loop. It can be a common mistake when writing a loop or conditional to forget to add curly braces after adding a second statement. For this reason, some programmers will use curly braces even for single statement loops and conditionals. The idea is that the code is more readable and easier to maintain, and so it is less prone to error.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.72.176