Skip to content

Instantly share code, notes, and snippets.

@CanTheAlmighty
Last active September 7, 2018 10:49
Show Gist options
  • Save CanTheAlmighty/e411590d2a48d2ec9fb1 to your computer and use it in GitHub Desktop.
Save CanTheAlmighty/e411590d2a48d2ec9fb1 to your computer and use it in GitHub Desktop.
StackOverflow Function Pointers
//
// main.c
// ObviousHomeworkFucboi
//
// Created by Can on 3/9/15.
// Copyright (c) 2015 Can. All rights reserved.
//
#include <stdio.h>
typedef int (*operation)(int, int);
int add(int a, int b) { return a+b; }
int substract(int a, int b) { return a-b; }
int multiply(int a, int b) { return a*b; }
int divide(int a, int b) { return a/b; }
operation operations[] = {add, substract, multiply, divide};
enum OperationIndex
{
Addition = 1,
Substraction,
Multiplication,
Division
};
int operate(enum OperationIndex type, int left, int right)
{
operation selected = operations[(type-1)%4];
return (*selected)(left, right);
}
int main(int argc, const char * argv[])
{
printf("%d", operate(Addition, 2, 4));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment