Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29275 Discussions

Question about the "intent" statement

Gustavo_Colvero
Beginner
639 Views
Hi,

I have this doubt concerning the intent statement for arguments on
subroutines: until now, I thought that INTENT(IN) was some kind of
safeguard to the argument, but I got surprised with the behaviour of
the following piece of code:

[fortran]program test
  implicit none
  interface
    subroutine hmmm(x)
       implicit none
       double precision, intent(in) :: x
       double precision, pointer :: y=>null()
    end subroutine hmmm
  end interface
  double precision :: x

  x = 2.0d0
  call hmmm(x)

  write(*,*)x

end program test


subroutine hmmm(x)
   implicit none
   double precision, target, intent(in) :: x
   double precision, pointer :: y=>null()
   y => x
   y = 3.0d0
end subroutine hmmm[/fortran]

Well, it's in fact assigning 3 to x.

I have read the entries

Argument Association and Argument Association in Procedures

on the composerxe documentation but its not clear to me if I should
expect just this. Note also that the actual argument doesn't have the
target arrtibute.

Thanks for any enlightenment here.
Gustavo.

0 Kudos
4 Replies
Steven_L_Intel1
Employee
639 Views
Your program lies to the compiler about the interface of the subroutine. If you compile with "-warn interface" it will even tell you this. You left off the TARGET attribute in the interface block and this is one of the things that triggers the requirement of an explicit interface.

However... The INTENT(IN) attribute only prevents you from using x in a way where it is directly redefined, such as in an assignment. As you see, you can get around that with a pointer assignment - or really, any number of other ways. INTENT is the programmer's promise to the compiler. The compiler is required to complain if you use the argument in contexts where it is changed directly, but not through indirect means. You broke the promise and all bets are off.
0 Kudos
Gustavo_Colvero
Beginner
639 Views
Thanks for the quick reply!

In this case is there any attribute or statement for the actual
argument to be sure it won't be modified by a subprogram?

Thanks again.
Gustavo.
0 Kudos
Steven_L_Intel1
Employee
639 Views
You could pass (x), which would pass a temporary copy of x. (The standard doesn't actually require that, but that's how we implement it. There is no way to make it "read-only" against all possibilities.
0 Kudos
Gustavo_Colvero
Beginner
639 Views
Right.
Well, thanks once more. I really appreciated your help.

Cheers,
Gustavo.

PS: Just in case you're thinking "what kind of mess is he doing?" the thing
is that I'm trying to avoid problems using some 3rd party subroutines, which
are, in fact, unexpectedly changing the value of input parameters.
0 Kudos
Reply