Does the function pointer affect the run time of the program?
int (*fptr1)(int);
int square(int num) {
return num*num;
}
int main()
{
int n = 5;
fptr1 = square;
printf("%d squared is %d\n",n, fptr1(n));
return 0;
}
Does the function pointer affect the run time of the program?
int (*fptr1)(int);
int square(int num) {
return num*num;
}
int main()
{
int n = 5;
fptr1 = square;
printf("%d squared is %d\n",n, fptr1(n));
return 0;
}
This is kind of hard to answer, since it's very low level, and it generally boils down to "it depends".
In general, assuming the function pointer is actually used, I would expect it to have a cost since it's an extra step. There's a difference between loading the value of a variable and then jumping there, compared to jumping to a constant location that is known at load-time. That cost will probably vary over the execution of the program, due to caching for instance, but it will likely never be zero. Also using a function pointer might of course allow the code to be structured in a way that makes it faster overall, so it can still be a positive.
For instance, consider:
for (a bajillion)
{
if (something complex)
{
function1();
}
else
{
function2();
}
}
this does the complex if
a bajillion times, which of course will cost a lot. This can be refactored using function pointers:
const void (*function)(void) = (something complex) ? function1 : function2;
for (a bajillion times)
{
function();
}
The latter code moves the if
out of the loop by pre-computing which function to call, thus saving (a bajillion - 1) instances of the condition from ever being evaluated. This can be faster, even if the actual function call now is slower due to the extra indirection step.
For this specific case, compiling with optimization removes the call, and even removes the squaring itself since it's compile-time constant.
Aside from the fact that it is far less likely that a compiler will inline the function, no.
Note that the as-if rule allows the compiler to generate code as if the source was
int main()
{
printf("5 squared is 25\n");
}
epitomising the fact that many optimisations are best left to the compiler.
Yes. One of the major advantage of function pointers is runtime polymorphism.
You can use same function pointer to point to different functions with same signature.
Example:
int (*fptr1)(int);
int square(int num) {
return num*num;
}
int cube(int num)
{
return num*num*num;
}
int main()
{
int n = 5;
fptr1 = square;
printf("squre = %d\n", fptr1(n));
fptr1 = cube;
printf("cube= %d\n", fptr1(n));
return 0;
}
Here fptr1
is made to point to different functions(square
and cube
) based on the need.