Created
August 12, 2012 10:26
-
-
Save pkukielka/3331116 to your computer and use it in GitHub Desktop.
Factorial in C with trampolines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
typedef struct _trampoline_data { | |
void(*callback)(struct _trampoline_data*); | |
void* parameters; | |
} trampoline_data; | |
void trampoline(trampoline_data* data) { | |
while(data->callback != NULL) | |
data->callback(data); | |
} | |
//----------------------------------------- | |
typedef struct _factorialParameters { | |
int n; | |
int sum; | |
} factorialParameters; | |
void factorial(trampoline_data* data) { | |
factorialParameters* parameters = (factorialParameters*) data->parameters; | |
if (parameters->n <= 1) { | |
data->callback = NULL; | |
} | |
else { | |
parameters->sum *= parameters->n; | |
parameters->n--; | |
} | |
} | |
int main() { | |
factorialParameters params = {5, 1}; | |
trampoline_data t = {&factorial, ¶ms}; | |
trampoline(&t); | |
printf("\n%d\n", params.sum); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment