[ create a new paste ] login | about

Link: http://codepad.org/BNKO5dRQ    [ raw code | output | fork ]

AaronMiller - C, pasted on Feb 29:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* tester functions */
int GetSum(int x, int y) { return x + y; }
int GetDif(int x, int y) { return x - y; }

/* "load" one of the functions */
void(*Sym(const char *n))() {
  if (!strcmp(n, "GetSum")) return (void(*)())GetSum;
  if (!strcmp(n, "GetDif")) return (void(*)())GetDif;

  return (void(*)())0;
}

/* display an error message */
void Error(const char *message) {
  fprintf(stderr, "%s\n", message);
  exit(1);
}

/* ---- MEANINGFUL CODE BELOW ---- */

/* Use this to define a function pointer (pass to FN_LIST) */
#define FN_DEF(n,r,p) r(*fn_##n)p;

/* Use this to grab a function pointer using "Sym" */
#define FN_GET(n,r,p) if(!((*(void(**)())&fn_##n)=Sym(#n))){Error("Failed to load " #n);}

/* Define your functions in this list; name, return type, (args) */
#define FN_LIST(F) F(GetSum,int,(int, int))\
                   F(GetDif,int,(int, int))

/* Define all of the function pointers here */
FN_LIST(FN_DEF);

/* Initialization routine (load all the function pointers) */
void Init() {
  FN_LIST(FN_GET);
}

/* Main routine */
int main() {
  int x, y;

  /* load the functions in FN_LIST */
  Init();

  /* prepare values for the loaded functions */
  x = 3;
  y = 1;

  /* call the loaded functions */
  printf("%i + %i = %i\n", x, y, fn_GetSum(x, y));
  printf("%i - %i = %i\n", x, y, fn_GetDif(x, y));

  /* done */
  return 0;
}


Output:
1
2
3 + 1 = 4
3 - 1 = 2


Create a new paste based on this one


Comments: