2011年1月11日 星期二

A program that prints itself

#include <stdio.h>
#include <assert.h>
int main(void)
{
  FILE *fp;
  int c;
  fp = fopen(__FILE__, "r");
  assert(fp != NULL);
  while ((c = fgetc(fp)) != EOF)
    putchar(c);
  fclose(fp);
  return 0;
}

Subtraction as a comparator

This is why you should not use subtraction as a comparator.

http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

/* qsort example */
#include <stdio.h>
#include <stdlib.h>

int values[] = {-2147483640, 50, 100};

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}

int main ()
{
  int n;
  qsort (values, 3, sizeof(int), compare);
  for (n = 0; n < 3 ; n++)
     printf ("%d ",values[n]);
  return 0;
}

The output is.

50 100 -2147483640