2.1.16. Code Formatting

There is a saying - Code is poetry. [1] (But, it depends on the Poet how Beautful that Poem is!)

The code is written for the compiler. But in long term, programmers have to read that code again and again. C Language is very flexible and forgiving. A piece of code that takes seconds for a compiler to interpret may take an eternity [2] for a programmer to understand.

Consider the code example below.

void f1() {
  return;
}

int f2()
{ return 0; }

int f3() { return 1; }

int f4(int k)
{
        if (k > 100) {
    return 3; } else k++;
        return k;
}

In the above example, f1(), f2(), f3() are written in a separate coding style. Few programmers may have issue with that coding convention. Others may just ignore it. But every one would agree that f4() is written poorly.

int f5(int k, int m) {
    if ( k > 100 )
         k++;
         m++;
    if ( m < 100 )
         return --m;
}

For that matter, f5() is just killing the C Language. Wrong indentation may force some users to oversee obvious mistakes.

int f4(int k) {
    if (k > 100) {
        return 3;
    } else
        k++;
    return k;
}

The reformatted f4() looks more understandable. Eclipse can do this kind of beautification automatically. Select the code format and just press Ctrl + Shift + F OR Edit → Format. Eclipse would automatically fix the formatting.

But the best advantage with Eclipse is that it provides a great control over formatting. This is covered in depth in Code Style in Editing Code

[1]I don’t know the original source of that quote; but its tagline of http://wordpress.org.
[2]Almost an eternity. If you still don’t agree, try to understand the code at The International Obfuscated C Code Contest