In the first lecture, I showed a small C program (that should also make sense to Java programmers), computing integer powers of 2, and its compilation to x86 machine code. Here is the example in full.


#include < stdio.h >

int testfun( int n ){
  int res = 1;
  while( n > 0 ){
    n--;
    res *= 2;
  }
  return res;
}

int main( int argc, char** argv ) {
  for ( int i = 0; i < 10; ++i ) {
    int res = testfun ( i );
    printf ( "2^%i = %i\n", i, res );
  }
  return 0;
}

I compiled this program as follows.

   clang -S -Wall -O3 -std=c99 test.c

The clang compiler is free, open source software and available for most platforms. The -S option tells the compiler to generate assembly code, rather than machine code. The -Wall option tells the compiler to be really pedantic and report even minor violations of the C99 standart, which is switched on by the -std=c99 flag. Finally, the -O3 option tells the compiler to use optimisation level 3. If you don't use -O3 you should get simpler code.

The resulting x86 machine code can be found here. Quite a blow-up in terms of size from the original program.