Fortran pointer assignment, difference between "=>" and "="

Viewed 374

I am struggling to understand the different behavior of => and = when assigning one pointer to another in Fortran 95. I.e. say I have a derived data type foo, what then is the difference between the last two lines in the following snippet, are they equivalent?

type(foo), target :: f
type(foo), pointer :: p1, p2

f = foo(...)
p1 => foo

p2 => p1
p2 = p1
1 Answers

No, they are absolutely not equivalent and mistaking them has large consequences (like Fortran Functions with a pointer result in a normal assignment).

= is the assignment of value (or just assignment if you want to be exact), it will take the value stored on the right hand side and copy it to the left hand side. If the left hand side is a pointer, it will copy the value to the target of the pointer. If the pointer did not point anywhere (null) or to some undefined place (a garbage address), it is an undefined behaviour but a crash is very likely.

=> is the pointer assignment, the left hand side must be a pointer, the right hand side must be a target or a pointer. The pointer on the left hand side will point to the target (or the target of the pointer) on the right hand side. If the pointer on the left was already pointing to some memory, that was previously allocated by an allocate statement through a pointer, and it was the only pointer pointing there, that memory will be lost (a memory leak).

Related