May 30, 2016 at 1:54am UTC
What type does auto stand for here in lines 24 and 40? How does it appear in the code if it were written without auto?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include<iostream>
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide (int x, int y)
{
return x/y;
}
auto getArithmeticFunction(char op)
{
switch (op)
{
case '+' : return &add;
case '-' : return &subtract;
case '/' : return ÷
case '*' : return &multiply;
}
}
int main()
{
char op;
std::cout<<"input operator :" ;
std::cin>>op;
auto func = getArithmeticFunction(op);
std::cout << func(10,5) << std::endl;
return 0;
}
Thx
Last edited on May 30, 2016 at 1:58am UTC
May 30, 2016 at 2:08am UTC
The type of the functions it returns is:
int (*)(int, int)
May 30, 2016 at 6:55pm UTC
Hi,
Yours is a more straightforward way of dealing with auto in this case. I also found this to be useful, a typedef: which is similar to your tweak as well?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include<iostream>
typedef int (*arithmeticFcn)(int , int );
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide (int x, int y)
{
return x/y;
}
arithmeticFcn getArithmeticFunction(char op)
{
switch (op)
{
case '+' : return &add;
case '-' : return &subtract;
case '/' : return ÷
case '*' : return &multiply;
default : return nullptr ;
}
}
int main()
{
char op;
std::cout<<"input operator :" ;
std::cin>>op;
arithmeticFcn func = getArithmeticFunction(op);
std::cout << func(10,5) << std::endl;
return 0;
}
Last edited on May 30, 2016 at 6:59pm UTC
May 31, 2016 at 1:03am UTC
There is no difference between the type alias declaration using arithmeticFcn = int(*)(int,int);
and the typedef declaration typedef int (*arithmeticFcn)(int, int);