Fortran Functions with a pointer result in a normal assignment
Asked Answered
C

1

1

After some discussion on the question found here Correct execution of Final routine in Fortran I thought it will be useful to know when a function with a pointer result is appropriate to use with a normal or a pointer assignment. For example, given this simple function

 function pointer_result(this)
 implicit none 
 type(test_type),intent(in) pointer :: this 
 type(test_type), pointer :: pointer_result 

 allocate(pointer_result)
 end function 

I would normally do test=>pointer_result(test), where test has been declared with the pointer attribute. While the normal assignment test=pointer_result(test) is legal it means something different.

What does the normal assignment imply compared to the pointer assignment?

When does it make sense to use one or the other assignment?

Cetinje answered 30/12, 2018 at 8:47 Comment(2)
Do you know the difference between assignment and pointer assignment? If you do, can you explain more about what your final question is wanting?Letta
I think, a pointer assignment is when you associate a pointer to the right hand side, which could be an expression, routine, variable etc. But not sure what it really means when you do normal assignment. What I want is to know what the normal assignment really mean, what it implies and when is it useful to use it - and here specifically with application to functions with pointer results.Cetinje
S
3

A normal assignment

test = pointer_result()

means that the value of the current target of test will be overwritten by the value pointed to by the resulting pointer. If test points to some invalid address (is undefined or null) the program will crash or produce undefined results. The anonymous target allocated by the function will have no pointer to it any more and the memory will be leaked.

There is hardly any legitimate use for this, but it is likely to happen when one makes a typo and writes = instead of =>. It is a very easy one to make and several style guides recommend to never use pointer functions.

Selfinduction answered 30/12, 2018 at 9:18 Comment(2)
Thanks that made it quite more clearer regarding the differences. But I was told that there could be some cases where the normal assignment could be useful, Don't know what they could be, though.Cetinje
@A2LBK Perhaps between pointer variables, to copy the value. I can't imagine it for a pointer returning function.Crimpy

© 2022 - 2024 — McMap. All rights reserved.