+ 4
Function pointer with default arguments
Please refer below code : #include <iostream> using namespace std; int sum(int a , int b = 5) { return a + b; } int main() { int (*fp)(int ,int);//function pointer fp = ∑ //int result = fp(3,5); int result = fp(3); cout << result; return 0; } I am not able to call function pointer with default argument. Is there any other way we need to declare function pointer with default argument?
8 Answers
+ 5
It seems default parameters mean something only to us and the compiler. They play no part in the function signature, and thus are ignored when you assign the function to a function pointer or a std::function object.
Here are more details on the same:
https://stackoverflow.com/questions/2576411/function-pointers-with-default-parameters-in-c
https://stackoverflow.com/questions/10718994/can-i-bind-to-a-function-that-takes-default-arguments-and-then-call-it
You can maybe define a class that stores the previous state of the argument and in case no new argument is provided, you use the old argument.
+ 5
/*Fill in the blanks to declare a function sum returning the sum of its arguments and declare a function pointer psum pointing to sum.*/
int sum(int a, int b) {
return a + b;
}
int (*psum)(int, int) = sum;
+ 2
// suppose f1, f2, and f3 are declared
void (*funcs[3])() = {f1, f2, f3};
for (int ix = 0; ix <
; ix++) {
[ix]();
}
0
int sum(int a, int b) {
return a
b;
}
int (
psum)(int,
) =
;
0
declare a function sum returning the sum of its arguments and declare a function pointer psum pointing to sum.
int sum(int a, int b) {
return a + b;
}
int (*psum)(int,int) =sum;
0
int sum(int a, int b) {
return a
+
b;
}
int (
*
psum)(int,
int
) =
sum
;
0
void (*funcs[3])() = {f1, f2, f3};
for (int ix = 0; ix <
; ix++) {
[ix]();
}
0
void (*funcs[3])() = {f1, f2, f3};
for (int ix = 0; ix <
; ix++) {
[ix]();
}