Type of type : copy or reference?

Hello !

I have a type(toto) and the variable var0
type(toto) :: var0

inside an other type(tata), I wish to have access to var0 so I introduce in this type the field

type tata
  ...
  type(toto) :: var0
  ...
end type

and when I create

type(tata) :: var1

I enter :

var1%var0 = var0

my question : is var1%var0 a copy of var0 or a link to var0 (i.e reference)

:crazy_face:

Neither. ā€œCopiesā€ and ā€œlinksā€ are not Fortran concepts.

1 Like

neither. var1 is a variable of type tata. var1%var0 is a component that is of type toto, completely independent from the variable var0.

1 Like

If you wish to have access to var0, the original, by reference from within the context of the a derived type variable var1 (which of of derived type tata), you can use a pointer. (I’m going out on a limb here because I don’t often use pointers, so I’m going by my understanding of how it should work.)

Declare var0 as a target using type(toto), target :: var0.

Define a member field within tata that is a pointer to a variable of type toto, such as type(toto), pointer :: any_name (it doesn’t have to be called var0).

Then associate the pointer using var1%any_name => var0.

If you’d rather have a copy of var0 then delete target and pointer from the above, and use = instead of =>.

Edit: This might be a clearer example.

module mymod

type a
  real :: y = 3.14
end type a

type b
  type(a), pointer :: g
end type b

type c
  type(a) :: h
end type c

end module mymod

use mymod

type(a), target :: x
type(b) :: w
type(c) :: z

w%g => x
z%h =  x

print *, 'Initial value'
print *, x   ! original variable
print *, w%g ! reference to original variable
print *, z%h ! copy of original variable

x%y = 6.28

print *
print *, 'Updated value'
print *, x   ! original variable
print *, w%g ! reference to original variable
print *, z%h ! copy of original variable

end

Results with gfortran:

 Initial value
   3.14000010
   3.14000010
   3.14000010

 Updated value
   6.28000021
   6.28000021
   3.14000010
1 Like

Thanks I am going to test that solution.

I asked that question because I am facing strange behavior with intel compilers but every thing is fine with gnu compilers (usually intel are more flexible that gnu compilers)

Attribute target seems to transform a variable as a pointer (without dimension).

Between contiguous, protected, target… I am a little bit confused with these attributes and I usually avoid using it in order to keep more simplicity in codes.

program test
  type :: t1
     real         :: np
     real,pointer :: p => null()
  end type t1
  type(t1), target :: x,y

  x=t1(10.0)
  x%p => x%np
  Print *,x%np, x%p

  y = x
  Print *,y%np, y%p

  x%np=5.0
  Print *,y%np, y%p

end program

As you can verify, the intrinsic assignment y=x produces the effect of intrinsic assignment for nonpointer components (informally, ā€˜copy’) and pointer assignment for pointer components (informally, ā€˜reference’).

1 Like