Jacob_DiDiodato

Function Pointer Example

Nov 5th, 2020
2,437
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.05 KB | None | 0 0
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stddef.h>
  5.  
  6. #define OP1 10
  7. #define OP2 5
  8.  
  9. int add(int op1, int op2)
  10. {
  11.     return op1 + op2;
  12. }
  13.  
  14. int sub(int op1, int op2)
  15. {
  16.     return op1 - op2;
  17. }
  18.  
  19. int div(int op1, int op2)
  20. {
  21.     return op1 / op2;
  22. }
  23.  
  24. int mul(int op1, int op2)
  25. {
  26.     return op1 * op2;
  27. }
  28.  
  29. /*
  30.  * Note: This function does not account for negative powers
  31.  */
  32. int myPow(int op1, int op2)
  33. {
  34.     int total = 1;
  35.     for(int i = 0; i < op2; i++)
  36.     {
  37.         total *= op1;
  38.     }
  39.     return total;
  40. }
  41.  
  42. int main(void)
  43. {
  44.     int (*operations[5])(int, int) = {add, sub, div, mul, myPow};
  45.     const char* loopkupTable = "+-/*^";
  46.    
  47.     while(true)
  48.     {
  49.         int opcode = getchar();
  50.         char* opStr = strchr(loopkupTable, opcode);
  51.         if (opStr == NULL)
  52.         {
  53.             printf("Opcode not in table.\n");
  54.         }
  55.         else
  56.         {
  57.             ptrdiff_t chosenOperaton = opStr - loopkupTable;
  58.             printf("Performing operation %c with ops %d and %d. ", *opStr, OP1, OP2);
  59.             printf("Output is %d.\n", operations[chosenOperaton](OP1, OP2));
  60.         }
  61.         getchar();
  62.     }
  63.    
  64.     return 0;
  65. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment