当前位置: 动力学知识库 > 问答 > 编程问答 >

c - How do i perform arithmetic operations with function pointers?

问题描述:

So..I understand that if i take(*ptr) as some function f then

res = (*ptr)(a,b) is the same as res = f(a,b).

So now my problem is that I have to read in 3 integers. First 2 are the operands, third is the operator e.g. 1 = add, 2 = subtract, 3 = multiply, 4 = divide. How do I do it without if or switch statements.

I was thinking of two possible solutions

  1. create 4 pointers and deference each pointer to an arithmetic operation, but with that I still have to do some sort of input

    validation which would require if or switch statements

  2. This isn't really a solution but the basic idea would probably by like. if c = operator then I can somehow do something like res =

    (*ptrc)(a,b) but I don't think there's such a syntax for C

Sample input

1 2 1

1 2 2

1 2 3

1 2 4

Sample Output

 3

-1

2

0

My Code :

#include <stdio.h>

//Datatype Declarations

typedef int (*arithFuncPtr)(int, int);

//Function Prototypes

int add(int x, int y);

int main()

{

int a, b, optype, res;

arithFuncPtr ptr;

//ptr points to the function add

ptr = add;

scanf("%i %i", &a, &b);

res = (*ptr)(a, b);

printf("%i\n", res);

return 0;

}

int add(int x, int y)

{

return x+y;

}

网友答案:

You may put you functions pointers in an array.

#include <stdio.h>

//Datatype Declarations
typedef int (*arithFuncPtr)(int, int);


//Function Prototypes
int add(int x, int y);
int sub(int x, int y);
int mul(int x, int y);
int div(int x, int y);

int main()
{
    int a, b, optype, res;

    arithFuncPtr ptr[4];

    //ptr points to the function
    ptr[0] = add;
    ptr[1] = sub;
    ptr[2] = mul;
    ptr[3] = div;

    scanf("%i %i %i", &a, &b, &optype);

    res = (ptr[optype - 1])(a, b);

    printf("%i\n", res);

    return 0;
}

int add(int x, int y)
{
    return x+y;
}  

int sub(int x, int y)
{
    return x-y;
}  

int mul(int x, int y)
{
    return x*y;
}  

int div(int x, int y)
{
    return x/y;
}  
分享给朋友:
您可能感兴趣的文章:
随机阅读: