If you look at the definition of the intrinsic function CEILING it has an optional parameter KIND which can be used to force the return value's integer kind.
Would there be any way to implement my own function in Fortran in such a way as to have the kind, or even better the type of the returned value of a function depend on a parameter? I've tried something like this:
program test_kind
use iso_fortran_env
implicit none
integer(kind=int32) :: a
print*, kind(a)
print*, kind(kt(int16))
print*, kind(kt(int32))
contains
function kt(kind)
implicit none
integer, intent(in) :: kind
integer(kind=kind) :: kt
kt = 100
end function kt
end program test_kind
But it fails with the error:
test_kind.f90:12:21:
integer(kind=kind) :: kt
1
Error: Parameter ‘kind’ at (1) has not been declared or is a variable,
which does not reduce to a constant expression
Now I know I can use procedure overloading to have the same name associated with different procedures depending on the types of arguments. But I'm asking whether the type of the return value can depend on the value of an argument.
No. It is not possible in the standard language, as of F2015 draft. The intrinsic procedures are special in this regard.
Dummy arguments that are data objects are always variables in non-intrinsic procedures.
Kind parameters must be given by constant expressions, and variables are not constants. The rules for nominating the type of an object in a scope are practically more restrictive.
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