Exercise 3-32 (FunctionPointer)
Chapter_3 Exercise_3-31 PointerToFunction | Exercise_3-33 |
Exercise 3-32 TCP1, p. 230
Exercise 3-32. Define a function that takes a double argument and returns an int. Create and initialize a pointer to this function, and call the function through your pointer.
FunctionPointer.cpp download
// Defining and using a pointer to a function
#include <iostream>
using std::cout;
using std::endl;
int truncate(double);
int main()
{
int (*fp1)(double); // Define a function pointer
fp1 = &truncate; // fp1 = truncate; // Initialize it
cout << (*fp1)(1.1) << endl; // Dereferencing calls the function, truncate()
cout << fp1(1.2) << endl; // alternate way to call the function
cout << (*truncate)(2.4) << endl;
cout << truncate(2.5) << endl;
int (*fp2)(double) = truncate; // Define and initialize
fp2 = fp1; // nothing changes, both pointers point to truncate()
// fp2 = &fp1; // compile error, both are pointers
cout << (*fp2)(1.5) << endl; // function call, truncate()
fp2 = &truncate;
cout << fp2(1.6) << endl; // same function call
return 0;
}
int truncate(double d)
{
return int(d); // (int)d;
}
/*
g++ FunctionPointer.cpp -o FunctionPointer
./FunctionPointer
1
1
2
2
1
1
*/
Note: See also ch3-PointerToFunction above.
Chapter_3 Exercise_3-31 PointerToFunction | BACK_TO_TOP | Exercise_3-33 |
Comments
Post a Comment