Exercise 3-33 (Complicated function pointer declaration)
Chapter_3 Exercise_3-32 | FunctionTable Exercise_3-34 |
Exercise 3-33 TCP1, p. 230
Exercise 3-33. Declare a pointer to a function taking an int argument and returning a pointer to a function that takes a char argument and returns a float.
ComplDecl.cpp download
#include <iostream>
using std::cout;
using std::endl;
float fc (char);
typedef float (*fpc)(char);
fpc fi (int);
int main()
{
float (*(*fpi)(int))(char); // complicated function pointer declaration
// fpc (*fpi)(int); // simpler alternative declaration
fpi = &fi; // fpi = fi; // initialize pointer
fpc a = (*fpi)(0);
a = &fc; // a = fc;
cout << "(*a)(0): " << (*a)(0) << ", a(1): " << a(1) << endl;
fpc b = fpi(1);
b = fc; // b = &fc;
cout << "(*b)(0): " << (*b)(0) << ", b(1): " << b(1) << endl;
a = (*fi)(0);
a = fc;
cout << "(*a)(1): " << (*a)(1) << ", a(2): " << a(2) << endl;
b = fi(1);
b = &fc;
cout << "(*b)(1): " << (*b)(1) << ", b(2): " << b(2) << endl;
return 0;
}
float fc (char c)
{
float f = c*2;
return f;
}
fpc fi (int i)
{
fpc a;
cout << "fi(" << i << ")" << endl;
return a;
}
/*
g++ ComplDecl.cpp -o ComplDecl
./ComplDecl
fi(0)
(*a)(0): 0, a(1): 2
fi(1)
(*b)(0): 0, b(1): 2
fi(0)
(*a)(1): 2, a(2): 4
fi(1)
(*b)(1): 2, b(2): 4
*/
Note: See also ch3-ComplicatedDefinitions above.
Chapter_3 Exercise_3-32 | BACK_TO_TOP | FunctionTable Exercise_3-34 |
Comments
Post a Comment