Pages

Wednesday, June 8, 2011

Formatting C / C++ code

Formatting C / C++ code

by: WaltP - Aug 11, 2005
(ref: http://www.gidnetwork.com/b-38.html)
To help understand the flow of your C/C++ code, whitespace (spaces, tabs, new lines) are all ignored by the compiler, which means you can scatter this whitespace all over your code and make it readable by everyone. This is especially helpful when asking for help on forums. Very few want to read code that has no formatting. It makes the code hard to understand. Also, lack of formatting make some errors nearly invisibe, like mismatched braces, parentheses, and so on.

For example, everyone knows the "Hello World" program. This is a legal form of the program:


C/CPP/C++ Code Example:
#include <stdio.h>
int main(){printf("Hello World\n");return(0);}

As you can see, it's a little hard to read. Imagine a larger program...
The following are some suggestions and tips on formatting your C/C++ code. These are simply my preferences and in no way imply a standard. After 20+ years of programming, these are some of the things I do to keep my sanity.

Whitespace

Sprinkle it anywhere it can aid in understanding:


C/CPP/C++ Code Example:
if (i == 10 && j < 22) printf("%d %d\n", tval1, tval2);

instead of


C/CPP/C++ Code Example:
if(i==10&&j<22)printf("%d %d\n",tval1,tval2);

Small but useful. Definitely place whitespace between terms in statements, and in many cases between the operators.

Parentheses

Use them every chance you can to clear up any ambiguity. Many people learn the equation:


C/CPP/C++ Code Example:
rval = 1 + rand() % 10  // get a random value between 1 and 10

There is no ambiguity to the compiler, but by us humans, is it


C/CPP/C++ Code Example:
a:  (1 + rand()) % 10   // or
b:   1 + (rand() % 10)  // ??

The answer of course is b thanks to operator hierarchy, but as a code reader it helps to add the parens to clear up any possible confusion.

Long Lines

Break these up into separate lines. If a line is much greater that 70-85 characters, consider splitting the line into multiple lines. An if with multiple && and || can be placed into one statement, but there is no need for:


C/CPP/C++ Code Example:
if (((test1 > 10) && (test1 < 25)) || ((test2 < 10) && (test2 > -2)) || ((test3 == 7) || (test3 == 1)))

Break this if into lines:


C/CPP/C++ Code Example:
if (((test1 > 10) && (test1 < 25)) || 
    ((test2 < 10) && (test2 > -2)) ||
    ((test3 == 7) || (test3 == 1)))

I like to leave an operator at the end as above and indent each line to keep segments of the if lined up. Whitespace may have to be sprinkled to keep sections lined up.
I've seen code that has over 200 characters in one line. These can easily be broken up into multiple lines for readability.

Indentation


The biggest aid to understanding. Indent blocks of code 3 to 4 spaces. 2 is not quite enough, 5 is getting too much. Try not to use tabs because:
  1. different programs may display tabs differently
  2. most forums handle tabs badly
Usually tabs are 8 spaces, which means a 4th-block indent starts 32 spaces from the left border, which in itself makes code hard to read. Too much of a good thing...
The format I use is:


C/CPP/C++ Code Example:
int main()
{
    int   val;          // I like to line up the variable names
    int   i,j;
    char  buf[20];
    char *p
    
    for (i=1; i<5; i++)                   // loop to get 5 names
    {
        printf("Enter your name: ");
        fgets (buf, sizeof(buf), stdin);    // get the name
        p = buf;                            // set pointer p to begin of buf
        while (*p)                          // loop until end of string
        {
            if ((*p >= 'a')  &&             // check for lower case characters
                (*p <= 'z'))
            {
                *p -= 32;                   // change lower case to upper
            }
            p++;                            // next character
        }
    }
    printf("Program done...");
}


Make all the block indentation consistant. I prefer the above format for the braces. Other options are:


C/CPP/C++ Code Example:
if (a == b) {
    c = b * 2
}

or


C/CPP/C++ Code Example:
if (a == b) 
    {
    c = b * 2
    }

Neither of which I personally care for.
But bottom line:
  • each and every time you use an open-brace, indent everything following.
  • each and every time you use a close-brace, un-indent everything following.
Also consider that the whileforifswitch, etc. statements are compound statements. All the code between the braces following an if statement are effectively the statement pertaining to the if. In other words,


C/CPP/C++ Code Example:
if (rtn == 0) 
{
    // --code--
}

no matter how many statements are contained in --code--, everything within the braces should be considered one statement.
But in some cases, the braces are sometimes omitted. For example, if there is only one statement to be executed:


C/CPP/C++ Code Example:
if (rtn == 0) 
{
    return 5;
}
C/CPP/C++ Code Example:
if (rtn == 0) 
    return 5;
C/CPP/C++ Code Example:
if (rtn == 0) return 5;

are all virtually identical. The only real benefit to the first form is that during the debug phase, it's easy to add test statements to the code without a lot of hassle. Otherwise, I personally prefer the third form if the statement is small. And with an else I use:


C/CPP/C++ Code Example:
if (rtn == 0) return 5;
    else      testval = 12;

for single ifs, and


C/CPP/C++ Code Example:
if (rtn == 0) 
{
    return 5;
}
else
{
    testval = 12;
}

for the multiple.
In my opinion,
  • no matter how big or small the program is,
  • whether production code or quickie throw-away test
get in the habit of proper indentation. If you don't use a programming IDE (Integrated Development Environment) when developing your code, there are many programming editors available that do automatic indentation to aid the programmer. Some free, some shareware. Google is your friend ;)

Problems / Limitations

There are many more formatting options that should be considered. These are just a few of the more obvious areas where formatting makes the biggest impact on readability.
DSmith posted a link to a style document here that would be worth checking out. You can find many other references on the internet to help you develop your own coding style.

No comments:

Post a Comment