Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>//printf to use
- #include <stdlib.h>//atof to use, atof convert string to float
- //we need to typedef function pointer
- typedef float (*functionPointerType)(float, float);// now i have a type, let's use it
- int getOperatorIndex(char operator); //signature
- //Our basic arithmetic operation
- float plus(float a, float b){return a + b;}
- float minus(float a, float b) { return a - b; }
- float multiply(float a, float b) { return a * b; }
- float divide(float a, float b) { return a / b; }
- //now let's buil our calculator
- //this function will return function pointer
- functionPointerType calculator(float a, char operator, float b){ //here ccharIndex is this index we just talk about
- //our function pointer array:
- int charIndex = getOperatorIndex(operator);
- functionPointerType arrayFunctionPointer[]= {plus, minus, multiply, divide}; //simply their name
- return arrayFunctionPointer[charIndex]; //so it returns function pointer
- }
- //this function will gives us index of each operators in ou opcodes array
- int getOperatorIndex(char operator){
- //our operators:
- char opcodes[] = {'+', '-', '*', '/', '\0'}; //or simply opcodes[]= "+-*/"
- int i = -1;
- while(opcodes[++i]){
- if(opcodes[i] == operator)
- return i;
- }
- return -1; //if error in operator
- }
- //in main, let's use command line arguments
- int main(int argc, char **argv){
- //Usage: ./a.out 5 / 2 = 2.5 (for example), so argc equals 4
- if(argc == 4){
- float a = atof(argv[1]); //in above exaple it is 5
- char operator = argv[2][0]; //in above exaple it is divide character, index zero because it is string in command line
- float b = atof(argv[3]); //in above exaple it is 2
- functionPointerType f = calculator(a, operator, b ); //now we have suitable function
- //display result
- printf ("%f %c %f = %f\n", a, operator, b, f(a, b)); //or (*f)(a, b) the same
- }
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement