Skip to content

Instantly share code, notes, and snippets.

@muromtsev
Created March 3, 2024 08:53
Show Gist options
  • Save muromtsev/58cdebeb183c14eff682ba79b1e4d54b to your computer and use it in GitHub Desktop.
Save muromtsev/58cdebeb183c14eff682ba79b1e4d54b to your computer and use it in GitHub Desktop.
Calculator (Pointers to functions)
#include <iostream>
int add(int x, int y){ return x + y; }
int multiply(int x, int y){ return x * y; }
int subtract(int x, int y){ return x - y; }
int divide(int x, int y){ return x / y; }
typedef int (*arithmeticFcn)(int, int);
struct arithmeticStruct
{
char s;
arithmeticFcn fcn;
};
static arithmeticStruct arithmeticArray[] = {
{ '+', add },
{ '-', subtract },
{ '*', multiply},
{ '/', divide }
};
arithmeticFcn getArithmeticFcn(char s)
{
for(auto &arith : arithmeticArray)
{
if(arith.s == s)
return arith.fcn;
}
return add;
}
int main()
{
int a;
int b;
std::cout << "a: ";
std::cin >> a;
std::cout << "b: ";
std::cin >> b;
char c;
do
{
std::cout << "Enter an operation ('+', '-', '*', '/'): ";
std::cin >> c;
if(c == '+' or c == '-' or c == '*' or c == '/')
break;
else
continue;
} while(true);
arithmeticFcn fcn = getArithmeticFcn(c);
std::cout << a << ' ' << c << ' ' << b << " = " << fcn(a, b) << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment