Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Associated pointers in derived type? gFortran vs. Intel

I would like to check if a pointer inside a derived type has already been defined or not. I wrote the following simple code to show you my problem:

program test
implicit none

type y
    real(8), pointer :: x(:)
end type y
type(y), pointer :: w(:)

allocate(w(2))
allocate(w(1)%x(2))

write(*,*) associated(w(1)%x), associated(w(2)%x)

end program test

Compiling this code with gFortran 4.4.1 and running it on Ubuntu gives the result:

T F

whereas the same code compiled on Windows Vista with the Intel Fortran compiler 11.0 provides:

T T

The first result (gFortran) is what I am actually expecting. But the fact that the Intel compiler provides a different result makes me fear my code might not be correct. Am I doing something terribly wrong with the pointers in this example? Any idea or explanation?

Many thanks in advance for your help!

like image 460
remek Avatar asked Dec 15 '09 18:12

remek


1 Answers

You are testing to see if a pointer is associated without explicitly using nullify on the pointers. A great page on common Fortran mistakes remarks (with the code sample removed):

Many people think that the status of a pointer which has never been associated is .not. associated. This is false. (...) When a pointer is declared its status is undefined, and cannot be safely queried with the associated intrinsic.

It looks like the gfortran compiler may be set up to explicitly nullify pointers on declaration - you should probably think of this like the compiler automatically setting declared variables to zero, and not count on that behavior. If you want to be sure, you will nullify it yourself.

Edit:

I'm reading through the Intel compiler guide, and it specifies how to make sure that the pointer is nullified correctly - you can set up your derived type as

type y
    real(8), pointer :: x(:) => null()
end type y

Note, however, that it seems like this is limited to Fortran 95, as mentioned in the linked article.

like image 177
Tim Whitcomb Avatar answered Oct 21 '22 03:10

Tim Whitcomb