Jacob_DiDiodato icon

Function Pointer Example

Jacob_DiDiodato | PRO | 11/05/20 07:17:27 PM UTC | 0 ⭐ | 2377 👁️ | Never ⏰ | []
C |

1.05 KB

|

None

|

0 👍

/

0 👎

#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stddef.h>
 
#define OP1 10
#define OP2 5
 
int add(int op1, int op2)
{
    return op1 + op2;
}
 
int sub(int op1, int op2)
{
    return op1 - op2;
}
 
int div(int op1, int op2)
{
    return op1 / op2;
}
 
int mul(int op1, int op2)
{
    return op1 * op2;
}
 
/*
 * Note: This function does not account for negative powers
 */
int myPow(int op1, int op2)
{
    int total = 1;
    for(int i = 0; i < op2; i++)
    {
        total *= op1;
    }
    return total;
}
 
int main(void)
{
    int (*operations[5])(int, int) = {add, sub, div, mul, myPow};
    const char* loopkupTable = "+-/*^";
    
    while(true)
    {
        int opcode = getchar();
        char* opStr = strchr(loopkupTable, opcode);
        if (opStr == NULL)
        {
            printf("Opcode not in table.\n");
        }
        else
        {
            ptrdiff_t chosenOperaton = opStr - loopkupTable;
            printf("Performing operation %c with ops %d and %d. ", *opStr, OP1, OP2);
            printf("Output is %d.\n", operations[chosenOperaton](OP1, OP2));
        }
        getchar();
    }
    
    return 0;
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎