Sign up for Linode and get a 60-day $100 credit

The evolution of a C programmer

[ ↑ Go up a level ]  [ next page → ]

Advertisement space · 468×60

Every C programmer grows up eventually. Here's the same function, factorial(6), as written at each stage of the journey.

/* Newbie programmer */
#include <stdio.h>

int factorial(int x) {
    if (x == 0) {
        return 1;
    } else {
        return x * factorial(x - 1);
    }
}

int main(void) {
    printf("%d\n", factorial(6));
    return 0;
}
/* First year programmer, studied Python */
#include <stdio.h>

int main(void) {
    int result = 1;
    for (int i = 1; i <= 6; i = i + 1) {
        result = result * i;
    }
    printf("%d\n", result);
    return 0;
}
/* K&R purist */
#include <stdio.h>

int fact(n)
int n;
{
    return n ? n * fact(n - 1) : 1;
}

main()
{
    printf("%d\n", fact(6));
}
/* Discovered pointers */
#include <stdio.h>

void fact(int n, int *out) {
    for (*out = 1; n; *out *= n--)
        ;
}

int main(void) {
    int result;
    fact(6, &result);
    printf("%d\n", result);
    return 0;
}
/* Preprocessor wizard */
#include <stdio.h>

#define F0 1
#define F1 (1 * F0)
#define F2 (2 * F1)
#define F3 (3 * F2)
#define F4 (4 * F3)
#define F5 (5 * F4)
#define F6 (6 * F5)

int main(void) {
    printf("%d\n", F6); /* computed at compile time, as God intended */
    return 0;
}
/* Premature optimizer */
#include <stdio.h>

static const unsigned int FACTORIALS[] = {1, 1, 2, 6, 24, 120, 720};

int main(void) {
    printf("%u\n", FACTORIALS[6]); /* O(1) */
    return 0;
}
/* Embedded developer */
#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint16_t result = 1;   /* 720 fits; 9! doesn't. not my problem. */
    for (uint8_t i = 2; i <= 6; ++i)
        result *= i;
    printf("%u\n", (unsigned)result);
    return 0;
}
/* Obfuscated C contest entrant */
#include <stdio.h>
f(n,r){for(r=1;n;r*=n--);return r;}main(){printf("%d\n",f(6));}
/* EXPERT PROGRAMMER */
#include <stdio.h>
#include <math.h>

int main(void) {
    printf("%.0f\n", tgamma(7));
    return 0;
}

See also: the evolution of a Python, Ruby, JavaScript, PHP or Perl programmer, and where this joke started, Fritz Ruehr's The Evolution of a Haskell Programmer (itself a riff on the old "Hello World" Evolution of a Programmer).