Style

Practical C Programming chapter 3

Example of bad code: the international obfuscated C code contest and this program:

/*
 * HELLO WORLD program
 * by Jack Applin and Robert Heckendorn, 1985
 * (Note: depends on being able to modify elements of argv[],
 * which is not guaranteed by ANSI and often not possible.)
 */
main(v,c)char**c;{for(v[c++]="Hello, world!\n)";
(!!c)[*c]&&(v--||--c&&execlp(*c,*c,c[!!c]+!!c,!c));
**c=!c)write(!!*c,*c,!!**c);}

Here's another good one:

/*
 * Program to compute an approximation of pi
 * by Brian Westley, 1988
 * (requires pcc macro concatenation; try gcc -traditional-cpp)
 */

#define _ -F<00||--F-OO--;
int F=00,OO=00;
main(){F_OO();printf("%1.3f\n",4.*-F/OO/OO);}F_OO()
{
            _-_-_-_
       _-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
 _-_-_-_-_-_-_-_-_-_-_-_-_-_-_
  _-_-_-_-_-_-_-_-_-_-_-_-_-_
    _-_-_-_-_-_-_-_-_-_-_-_
        _-_-_-_-_-_-_-_
            _-_-_-_
}

Here's a more realistic example:

#include <stdio.h>
main()
{ int x=3;
printf("%d\n",((1<<x)-2)*7);
}

Which should have been written something like this:

/* This program calculates the value 6*7
 * by Hans Fugal
 */

#include <stdio.h>

int main()
{
    /* calculate the answer */
    int answer = 6*7;

    /* print it */
    printf("%d\n", answer);
}

Most importantly, KISS (keep it simple) and put some TLC (tender loving care) into the readability of your program. It will pay off for you and others when you revisit your code!