Last active
September 7, 2018 10:49
-
-
Save CanTheAlmighty/e411590d2a48d2ec9fb1 to your computer and use it in GitHub Desktop.
StackOverflow Function Pointers
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
// | |
// 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