c++ simple function dilemma -
i learning c++. here problem:
simple "calculator" program: read 2 numbers , sign, pass them function calculate, returns value or error, if forbiden char input. came 2 versions of function , don't know "right one". here are:
first 1 print directly, not practice (is it?).
void calculate(int x, int y, char s) { switch (s) { case ('+'): { std::cout << x + y << "\n"; } case ('-'): { std::cout << x - y << "\n"; } case ('*'): { std::cout << x * y << "\n"; } case ('/'): { std::cout << x / y << "\n"; } default: { std::cout << "wrong sign input. choose on of following four:+-*/\n"; } } } second 1 1 job yet, has flaw: if example input '5', '6', , '-' return -1 , handled mistake caller.
int calculate(int x, int y, char s) { switch (s) { case ('+'): { return x + y; } case ('-'): { return x - y; } case ('*'): { return x * y; } case ('/'): { return x / y; } default: { return -1; } } } what in given scenario?
output , calculation should separate functions. however, shouldn’t use special sentinel value indicate error if can valid output value.
the real problem input verification , calculation should also different functions. create enum potential operations, , pass in.
enum class operation { add, subtract, multiply, divide }; then have calculate take in operation. still need validate input somewhere, shouldn’t in same place.
you’ll still need default case in calculate, because enums can have values other declared ones, since should validating input elsewhere can make simple assert.
Comments
Post a Comment