Published by
Jul 21, 2010 (last update: Aug 6, 2011)

Cleaner code

Score: 3.8/5 (59 votes)
*****
The reason for me to write this article is the fact that many people don't seem to know (or care) about code readability. Readability is the base for portability, re-usability and understandability (!).
Without proper code you cannot ask help on these forums without getting complaints, so read carefully; these are some tips and tricks to clean up your code.

This is a guideline, I do not say this is perfect. I just place a good way to do it, it's up to you to decide if you use it or not.

This guide is not considered complete but should help you well on your way, all suggestions are welcome.

On Brackets Always put brackets on a empty line and put opening and closing brackets on the same "height" in your code. Anything that goes in between the two brackets should be tabbed to the right by a number which is consistent over all your code. (I use 4 spaces in my example) This style of bracketing is called, Allman style.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    for(int i = 0; i < 9; i++)
    {
        cout << i << endl;
    }
    return 0;
}

There are, of course, other ways to do this. One is a slight variation of the Allman style: Whitesmith style. The brackets are put on the same level as the inner statements.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

using std::cout;
using std::endl;

int main()
    {
    for(int i = 0; i < 9; i++)
        {
        cout << i << endl;
        }
    return 0;
    }

When it is not important to see the text clearly, but rather see how different statements relate to one another (mainly if/else relationships), you can also use 1TBS (The One True Brace Style):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    for(int i = 0; i < 9; i++)
    {
        // Allman, up to now, time to go 1TBS for If/Else
        if (i < 5) {
            cout << i << endl;
        } else {
            cout << i*2 << "\t";
        } // And of if/else clause, the last bracket is the only one that takes up it's own line
        // Allman again
    }
    return 0;
}


On Comments Commenting is done to improve readability, but it is also possible to make your comments more readable. Use multi-line comments only when needed and avoid putting comments at the end of code lines. Avoid tabbing your comments, use newlines to make things clearer. See On Consistency for more information.

The following comments may seem worthless, but I'm just trying to make clear what I told above.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using std::cout;
using std::endl;

int main()
{
    // Count
    for(int i = 0; i < 9; i++)
    {
        cout << i << endl;
    }

    // Program termination
    return 0;
}


On Consistency (General) When different alternatives achieve the same result (at the same speed and both in the same amount of code lines), assure that you remain consistent to a single method. This applies to post- and prefix additions and subtractions (++ / --), as well as functional and C-style conversions int() and (int).
Whatever you do, be consistent.

On Function Calls (and definitions) Be consistent with the way you call and define functions, for the sake of readability. There are not only a lot of ways to do the same, but also a lot of ways to write the same statement. When you form your own coding style, try to stick with one that allows you to keep things clear for yourself. There is no perfect way to write things in general, there are, however, good ways to write things for yourself. All of the below mentioned ways are legit.
1
2
3
power(3, 5)
power( 3,5 )
power(3,5)


On Initialization Consistency applies to initializations, too:
When given the choice between initializing at the start or later, use a single method. If you, however are left without a choice on which to use, use which ever you need. Furthermore, use proper spacing when creating pointers or references (or references to pointers to pointers to pointers to references to blablabla).
All of the following do the same (creating a reference to a pointer to a pointer to an integer called Variable). Whichever of these visualizes this structure to yourself the best is "the good way to go" for you. (There is NO wrong way, only "better" ways.)
1
2
3
4
int**& Variable;
int **& Variable;
int **&Variable;
int** &Variable;


On Naming
The following is a guideline and is open for change (as long as it's consistent, of course).

Naming is important for functions, classes, structures, unions, variables, namespaces and so on.
How to do good naming?
1. Make sure you name things by what they do (or are).
2. Possibly prefix them by a one or two lowercase character that describes the named instance. (c for classes, s for strings, i for integers, d for doubles, etc)
3. Start every word with a uppercase character and use lowercases for the rest. (An integer could become: iNumber)

A single exception to these rules are loop-variables. These are often named by a single lowercase character.

(All of this is just an observation of coding habits I have done for sometime. This is by no means a strict ruleset. It's more like a way to code that will easily be readable for anyone.)

On Operators Operators can be viewed as "editors" of "data". In this context it would be best to make clear sections as to organize this "data". This organization is subject to your own view on statements.
1
2
int iNumber = 6+5;
int iReturnValue = 4*iNumber +3;


On Preprocessor Directives All spacing and newline rules apply here. For #define, however, make sure you make them differentiable from normal variables (making their names entirely uppercase is one method to do so, pre- AND postfixing their names with _ is another. You are free to do whatever you want, just keep things clear.)


In the end, your programming style is something that shouldn't be forced upon you. However, keep in mind that to receive feedback for your code, people need to UNDERSTAND the code. If you want people to understand your code, make your code clear and easy to read.