is it possible to have function pointers in Fortran? Right now I have a code with some lines like this:
subroutine flag(iflag,a,b)
integer n, a, b, ii, iflag
do ii = 1, n
if (iflag.eq.0) a+b
else a-b
end do
return
end
The variable "n" has a huge value and so to run this code, I feel like I am wasting a lot of time with the "if" command. Is it possible to write something like a function pointer (I am not sure what I mean by that), such that at the code does something like this:
subroutine flag(iflag,a,b)
*depending on the iflag the subroutine flag is automatically
precompiled to call either flag_plus or flag_minus*
return
end
subroutine flag_plus(a,b)
integer n, a, b, ii
do ii = 1, n
a+b
end do
return
end
subroutine flag_minus(a,b)
integer n, a, b, ii
do ii = 1, n
a-b
end do
return
end
If it is possible I can save a lot of time by avoiding the "if" loop. Is anything like this remotely possible?
In Fortran 77 you can have a limited variant of function pointers, namely that you can pass the name of a procedure as an argument to another procedure (a function pointer, essentially). You cannot have a variable that contains the address of a procedure and then "call" that variable, though.
As of Fortran 2003, procedure pointer variables are part of the language.
That being said, I think your example problem could be solved even easier by something like
if (iflag == 0) then ! Why is iflag not of type logical?
do ii = 1, n
a + b
end do
else
do ii = 1, n
a - b
end do
end if
Make sure to profile it to see whether it has any effect, as well. Modern CPU's have pretty good branch predictors, and a branch test which doesn't change during the entire loop is pretty much the best case scenario (rule of thumb: predicted branches are close to free). Heck, your compiler might even be able to do the above kind of optimization..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With