Skip to content
Snippets Groups Projects
Commit 77e6ccfd authored by Simon Ebbers's avatar Simon Ebbers
Browse files

codestyle

parent f8f63d21
No related branches found
No related tags found
No related merge requests found
......@@ -9,73 +9,55 @@
/*
* Adds two integers
*/
int add(int a, int b) {
int res;
bool overflow = __builtin_sadd_overflow(a, b, &res);
if (overflow) {
throw std::invalid_argument("Malformed input. Integer overflow (add).");
}
return res;
int add(const int a, const int b) {
return a + b;
}
/*
* Multiplies two integers
* Subtracts integer b from integer a
*/
int multiply(int a, int b) {
int res;
bool overflow = __builtin_smul_overflow(a, b, &res);
if (overflow) {
throw std::invalid_argument("Malformed input. Multiplication error.");
}
return res;
int subtract(const int a, const int b) {
return b - a;
}
/*
* Subtracts integer b from integer a
* Multiplies two integers
*/
int subtract(int a, int b) {
int res;
bool overflow = __builtin_ssub_overflow(b, a, &res);
if (overflow) {
throw std::invalid_argument("Malformed input. Integer overflow (subtract).");
}
return res;
int multiply(const int a, const int b) {
return a * b;
}
/*
* Divides integer b from integer a, throwing an exception when b is zero.
* Throws an std::invalid_argument exceptions if invalid parameters are provided.
*/
int divide(int a, int b) {
int divide(const int a, const int b) {
if (b == 0) {
throw std::invalid_argument("Malformed input. Division by zero.");
throw std::invalid_argument("Tried to divide by 0.");
}
return a / b;
}
using binary_operator = decltype(&add);
std::unordered_map<char, binary_operator> map {
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide}
};
int evaluate(const std::string &s) {
int a, b;
decltype(map)::iterator iter;
std::stack<int> stack;
static const std::unordered_map<char, binary_operator> map {
{'+', add},
{'-', subtract},
{'*', multiply},
{'/', divide}
};
decltype(map)::iterator iter;
for (char c : s) {
if (std::isdigit(c)) {
stack.push(c - '0');
} else if (stack.size() >= 2 ) {
iter = map.find(c);
if (iter != map.end()) {
a = stack.top();
const auto a = stack.top();
stack.pop();
b = stack.top();
const auto b = stack.top();
stack.pop();
stack.push(iter->second(b, a));
} else {
......@@ -109,8 +91,8 @@ int main() {
} catch (const std::exception &e) {
std::cout << e.what();
}
if (result != INT_MAX) {
std::cout << "Result is: " << result << '\n';
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment