[J3] How to check if a function that returns an allocatable is actually allocated
Malcolm Cohen
malcolm at nag-j.co.jp
Wed Feb 5 23:07:49 UTC 2025
Hi Daniel,
It is easy for the compiler to raise a runtime error on return from function
foo, if the result is not allocated. The standard requires the result to be
allocated.
If the user function has such amazingly convoluted control flow that the
user cannot be 100% sure that it is allocated when he wants to return, he
can write "if (.not.allocated(foo)) error stop 'return from foo without
allocated'" himself.
Personally I think that the compiler should offer a checking option to
produce an explanatory runtime error - it's not like this is an expensive or
difficult check to perform. But running the program in a debugger lets one
get a traceback on the resulting seg fault if not.
Cheers,
--
..............Malcolm Cohen, NAG Oxford/Tokyo.
From: J3 <j3-bounces at mailman.j3-fortran.org> On Behalf Of Daniel Chen via J3
Sent: Thursday, February 6, 2025 2:39 AM
To: Van Snyder via J3 <j3 at mailman.j3-fortran.org>
Cc: Daniel Chen <cdchen at ca.ibm.com>
Subject: [J3] How to check if a function that returns an allocatable is
actually allocated
Hello all,
Consider the following code
```
print*, allocated(foo(.true.)) !! Not legal as intrinsic ALLOCATED
requires the
!! argument to have the ALLOCATABLE
attribute.
real, allocatable :: res !! The following 3 lines to workaround
it.
res = foo(.false.) !! Could be illegal too as reference to
foo is undefined.
print*, allocated(res)
contains
function foo(condition)
real, allocatable :: foo
logical :: condition
if (condition) then
allocate(foo)
foo = 1.0
end if
end
end
```
It seems there is not a "easy" way to check if the result of a function that
returns an allocatable is actually allocated as indicated in the code above.
My workaround seems have its own problem as the RHS of the intrinsic
assignment (reference to foo) is undefined.
Am I missing something here?
Thanks,
Daniel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.j3-fortran.org/pipermail/j3/attachments/20250206/c02758b3/attachment.htm>
More information about the J3
mailing list