0

I'm looking for a way to evaluate arithmetic operation using variable instead of operators. Here is an example:

char op1 = '+';
char op2 = '/';
int i = 0;
i = 4 op1 5 op2 3;

I've no idea if its possible in C. But, if its possible.. would be great. Thanks..

samaxI92
  • 11
  • 1
  • 4

2 Answers2

0

No, this isn't possible. When the C compiler parses the line of code, it treats operators and variables completely differently. There is no mechanism for interpreting a variable as an operator.

You can of course emulate the process with a function:

if ( op == '+' )
  return a+b;
else if ( op == '-' )
  return a-b;
else if . . .

but good luck with this when you have more than two operands.

rojomoke
  • 3,765
  • 2
  • 21
  • 30
0

There is one way you can look at this problem, yes you can use "if(random_var == '+')" or something similar or you can use a const defined variable:

#include<stdio.h>
#define plus +
#define minus -

main(){
printf("%d",5 plus 6 minus 1);
}

The output will be as expected 10 (5 + 6 - 1 = 10)

-> the const defined variables must be separated form the numbers