Skip to content

Instantly share code, notes, and snippets.

@marty1885
Created March 8, 2017 13:40
Show Gist options
  • Save marty1885/07088016725124edb6db1df29440a09f to your computer and use it in GitHub Desktop.
Save marty1885/07088016725124edb6db1df29440a09f to your computer and use it in GitHub Desktop.
#include <stdio.h>
//Implements a If() that works just like if in C
//Defines a function pointer type for our callback function
typedef void(*ConditionBranchFunc)(void* val);
//This If() takes in 4 parameters, tFunc is the function called when
// condition == 1. fFunc is called when condition == 0. condition is
// weathere the statement is true or false. dataPtr is a pointer that
// points to a data structure passed to tFunc and fFunc.
void If(ConditionBranchFunc tFunc, ConditionBranchFunc fFunc
, int condition, void* dataPtr)
{
ConditionBranchFunc func[2] = {fFunc,tFunc};
ConditionBranchFunc execFunc = func[condition];
execFunc(dataPtr);
}
//Prints an integer that is pointed by the pointer
void printInt(void* intPtr)
{
printf("%d\n",*(int*)intPtr);
}
//Does nothing
void foo(void* ptr)
{
}
//A structure that stores the data for the current state of executtion
// of the printing
typedef struct
{
int minVal;
int maxVal;
} Data;
//Dose the job of printing from maxVal to minVal
void executePrint(void* dataPtr)
{
Data dat;
Data* data = (Data*)dataPtr;
dat.minVal = data->minVal;
dat.maxVal = data->maxVal - 1;
If(printInt,foo,data->maxVal != 0,&(data->maxVal));
If(executePrint,foo,data->maxVal != 0,&dat);
}
//Swaps the value in the data structure passed in then print
void swapAndExecute(void* dataPtr)
{
Data* data = (Data*)dataPtr;
Data dat;
dat.minVal = data->maxVal;
dat.maxVal = data->minVal;
executePrint(&dat);
}
//The interface function. As the assignment requires
void p(int a, int b)
{
Data data;
data.minVal = b;
data.maxVal = a;
If(executePrint,swapAndExecute,a>b,&data);
}
int main()
{
p(5,1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment