Warior4356
Warior4356

Reputation: 27

Using a function in place of an operator

So I am trying to make a program that does math operations based on user input, however I am running into an issue with trying to set the math operator based on what they give.

Function:

const operator(int val)
{
    if (val == 1)
    {
    return +;
    }
    if (val == 2)
    {
    return -;
    }
}

With a main code looking something like this

scanf("%d", val)
output = 4 operator(val) 2
printf("%d", output)

Is there a variable type that I can use in place of an operator? If not is there a way to make a variable/function reference a defined macro?

For example:

#define plus +

then reference the macro in the code?

Finally I am aware I could have if cases for each input, however this scales poorly for something like,

output = 2 operator(val) 5 operator(val) 7 operator(val) 3 

which would require 64 if statements I think to make it work.

Thank you for reading, I am at my wits end on this.

Upvotes: 1

Views: 115

Answers (1)

grek40
grek40

Reputation: 13438

What you can do is using function pointers.

Lets say you are restricting yourself to integers and add / subtract for this example:

int add(int a, int b)
{
    return a + b;
}

int subtract(int a, int b)
{
    return a - b;
}

// without typedef, the signature of get_operator would be really messy
typedef int (*arithmetic_func)(int,int);

arithmetic_func get_operator(int val)
{
    if (val == 1)
    {
        return &add;
    }
    if (val == 2)
    {
        return &subtract;
    }
    return NULL; // what to do if no function matches?
}

Instead of output = 4 operator(val) 2 you can write:

output = get_operator(val)(4, 2)

What happens there is, that the get_operator(val) function call is returning a function pointer to an actual arithmetic function. Then this actual arithmetic function is called with the (4, 2) as parameters.

Upvotes: 5

Related Questions