Function Pointer
is a variable that stores the address of a function. Function pointers provide a way to call functions indirectly, making them a powerful and flexible feature.
Declaration Syntax:
Incrementing a pointer (ptr++) moves it to the next memory location, while decrementing (ptr--) moves it to the previous location.
int
(*
addPtr
)(
int
,
int
);
Initialization:
Initialize the function pointer by assigning it the address of a function with a matching signature.
int
add
(
int
a
,
int
b
) {
return
a
+
b
;
}
int
(*
funcPtr
)(
int
,
int
) =
add
;
Function Call:
calling a function through a function pointer involves using the function pointer as if it were a regular function. You can either use the dereference operator (*) or directly call the function pointer.
#include
<
stdio.h
>
Copy Code
int
add
(
int
a
,
int
b
) {
return
a
+
b
;
}
int
main
() {
int
(*
funcPtr
)(
int
,
int
) =
add
;
int
result
= (*
funcPtr
)(3, 5);
printf
("Result: %d
",
result
);
return
0;
}
In this example:
1. The add function adds two integers.
2. The funcPtr function pointer is declared and initialized to point to the add function.
3. The function pointer is used to call the add function, passing it two arguments (3 and 5).
4. The result is printed.
Both (*funcPtr)(3, 5) and funcPtr(3, 5) are valid ways to call a function through a function pointer. The compiler understands that the variable funcPtr is a function pointer and handles the call appropriately.
Passing Function Pointers as Arguments
Passing function pointers as arguments in C allows you to implement dynamic behavior by choosing which function to execute at runtime.
#include
<
stdio.h
>
Copy Code
int
add
(
int
a
,
int
b
) {
return
a
+
b
;
}
int
subtract
(
int
a
,
int
b
) {
return
a
-
b
;
}
int
operate
(
int
(*
operation
)(
int
,
int
),
int
a
,
int
b
) {
return
operation
(
a
,
b
);
}
int
main
() {
int
(*
addPtr
)(
int
,
int
) =
add
;
int
(*
subtractPtr
)(
int
,
int
) =
subtract
;
int
resultAdd
=
operate
(
addPtr
, 8, 3);
int
resultSubtract
=
operate
(
subtractPtr
, 8, 3);
printf
("Result of addition: %d
",
resultAdd
);
printf
("Result of subtraction: %d
",
resultSubtract
);
return
0;
}
This
example
defines two
functions
,
'add'
and
'subtract'
, for addition and subtraction. It introduces a generic 'operate'
functions
that takes a
functions pointer
along with two integers. In the
'main'
functions
, two
functions
pointers are declared and initialized to point to 'add' and 'subtract'. By invoking 'operate' with these
functions
pointers, the code dynamically selects and executes the desired operation, showcasing
flexibility
and
reusability
.