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

Update main.cpp

parent ad6abbac
No related branches found
No related tags found
No related merge requests found
......@@ -10,21 +10,36 @@
* Adds two integers
*/
int add(const int a, const int b) {
return a + b;
int res;
bool overflow = __builtin_sadd_overflow(a, b, &res);
if (overflow) {
throw std::invalid_argument("Malformed input. Integer overflow (add).");
}
return res;
}
/*
* Subtracts integer b from integer a
* Multiplies two integers
*/
int subtract(const int a, const int b) {
return b - a;
int multiply(const int a, const int b) {
int res;
bool overflow = __builtin_smul_overflow(a, b, &res);
if (overflow) {
throw std::invalid_argument("Malformed input. Multiplication error.");
}
return res;
}
/*
* Multiplies two integers
* Subtracts integer b from integer a
*/
int multiply(const int a, const int b) {
return a * b;
int subtract(const int a, const 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;
}
/*
......@@ -33,7 +48,7 @@ int multiply(const int a, const int b) {
*/
int divide(const int a, const int b) {
if (b == 0) {
throw std::invalid_argument("Tried to divide by 0.");
throw std::invalid_argument("Malformed input. Division by zero.");
}
return a / b;
}
......@@ -41,7 +56,6 @@ int divide(const int a, const int b) {
using binary_operator = decltype(&add);
int evaluate(const std::string &s) {
std::stack<int> stack;
static const std::unordered_map<char, binary_operator> map {
{'+', add},
{'-', subtract},
......@@ -49,6 +63,8 @@ int evaluate(const std::string &s) {
{'/', divide}
};
decltype(map)::iterator iter;
std::stack<int> stack;
for (char c : s) {
if (std::isdigit(c)) {
stack.push(c - '0');
......@@ -91,7 +107,6 @@ 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