First, the syntax
else (a == '/') return a/b;
wrong and should be
else if (a == '/') return a/b;
Secondly, your parameter a can take only 4 discrete values, so it is good practice to use an enumeration, for example
enum Operation { kAddition, kSubtraction, kMultiplication, kDivision }; int Compute(Operation a, int a, int b) { if (a == kAddition) return a+b; else if (a == kSubtraction) return ab; else if (a == kMultiplication) return a*b; else if (a == kDivision) return a/b; }
which ensures that the Compute user will use only one of these four values โโfor the operation parameter ( a ).
I probably have not used the best practices in my example, so I recommend that you read this answer for more details.
Finally, you can make the code shorter using the switch statement:
enum Operation { kAddition, kSubtraction, kMultiplication, kDivision }; int Compute(Operation a, int a, int b) { switch (a) { case kAddition: return a+b; case kSubtraction: return ab; case kMultiplication: return a*b; case kDivision: return a/b; } }
source share