Advertisement
tresonance

function_pointer_II

Jun 11th, 2020
1,392
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.96 KB | None | 0 0
  1. #include <stdio.h>//printf to use
  2. #include <stdlib.h>//atof to use, atof convert string to float
  3.  
  4. //we need to typedef function pointer
  5. typedef float (*functionPointerType)(float, float);// now i have a type, let's use it
  6.  
  7.  
  8. int getOperatorIndex(char operator); //signature
  9.  
  10. //Our basic arithmetic operation
  11. float plus(float a, float b){return a + b;}
  12. float minus(float a, float b) { return a - b; }
  13. float multiply(float a, float b) { return a * b; }
  14. float divide(float a, float b) { return a / b; }
  15.  
  16. //now let's buil our calculator
  17. //this function will return function pointer
  18. functionPointerType  calculator(float a, char operator, float b){ //here ccharIndex is this index we just talk about
  19.     //our function pointer array:
  20.     int charIndex = getOperatorIndex(operator);
  21.     functionPointerType arrayFunctionPointer[]= {plus, minus, multiply, divide}; //simply their name
  22.     return arrayFunctionPointer[charIndex]; //so it returns function pointer
  23. }
  24.  
  25. //this function will gives us index of each operators in ou opcodes array
  26. int getOperatorIndex(char operator){
  27.     //our operators:
  28.     char opcodes[] = {'+', '-', '*', '/', '\0'}; //or simply opcodes[]= "+-*/"
  29.     int i = -1;
  30.     while(opcodes[++i]){
  31.         if(opcodes[i] == operator)
  32.             return i;
  33.     }
  34.     return -1; //if error in operator
  35. }
  36.  
  37.  
  38. //in main, let's use command line arguments
  39. int main(int argc, char **argv){
  40.     //Usage: ./a.out 5 / 2 = 2.5 (for example), so argc equals 4
  41.     if(argc == 4){
  42.  
  43.         float a = atof(argv[1]); //in above exaple it is 5
  44.         char operator = argv[2][0];     //in above exaple it is divide character, index zero because it is string in command line
  45.         float b = atof(argv[3]); //in above exaple it is 2  
  46.         functionPointerType f = calculator(a, operator, b ); //now we have suitable function
  47.         //display result
  48.         printf ("%f %c %f = %f\n", a, operator, b, f(a, b)); //or (*f)(a, b) the same
  49.     }
  50.     return (0);
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement