How to use an array index as an operator?
Such that:
#include
main()
{
char sign[]={\'+\',\'-\'};
int a, b;
a = 12 sign[1] 10
The simplest is to use a switch statement or if-else chain.
#include
int main() {
char sign[]={'+','-'};
int a,b;
switch (sign[1]) {
case '+':
a = 12 + 10;
break;
case '-':
a = 12 - 10;
break;
}
printf("%d",a);
}
If I was doing this, I'd probably end up moving some of the logic into a function though. Perhaps something like this:
#include
int perform_operation(char op, int lhs, int rhs) {
switch (op) {
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
default:
return 0;
}
}
int main() {
char sign[]={'+','-'};
int a = perform_operation(sign[1], 12, 10);
printf("%d",a);
}