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

It seems there is no difference between intent(out) and intent(inout) declaration when passing a variable that already has a value.

vriesdwj
Beginner
500 Views
Please see sources attached:

program tst_intent1
! test intent(out) for variable that has already a value
real :: a
a = 5.0
write(*,*) 'intent1: ',a
call tst_intent2(a)
write(*,*) 'intent1: ',a
end program tst_intent1

subroutine tst_intent2(a)
! test intent(out) for variable that has already a value
real, intent(out) :: a
integer :: i ! switch to test two situations:
! i = 1 -> a gets the value 10; this value is returned to the main program.
! i = -1 -> a is not changed; an undefined value? is returned to the main program.
! Note that if intent(inout) is used, the input value of a is returned.
i = -1
if (i > 0) then
a = 10.0
write(*,*) 'ntent2: ',a
endif
end subroutine tst_intent2

If i = 1, in the main program "a" always gets the value 10
But if i = -1, in the main program "a" always has the value 5, even after returning for the subroutine. This is not what you schould expect because in the subroutine intent2 "a" should be a complete new variable according to the intent(out) declaration.

Is there a difference or should I always use intent(inout)?

Regards, Wilco de Vries
0 Kudos
1 Reply
Arjen_Markus
Honored Contributor I
500 Views
There _is_ a difference, but that may not be reflected in the actual values you get.
Intents define a kind of contract between parts of the code.

intent(in):
You have to guarantee that the variable has a definite value on input - that is the
responsability of the calling unit

intent(out):
The unit (subroutine, function) you call must make sure the variable has a value
upon return. If not, the compiler may detect that at compile time (but it is not
always possible to do so).
Furthermore an allocatable array or a pointer becomes unallocated/unasssociated
upon entry. It is the responsability of the unit to make sure that it becomes allocated/
associated upon return. With ordinary variables you ar not supposed to use the input
value.

intent(inout):
The variable has a value at entry and will have a (possibly different) value upon return.

These intents make it possible for the compiler to optimise things, but a scalar variable
simply has "a" value wen you look at the memory location it is associated with. So do
not expect an "undefined value" for an intent(out) variable - there simply is none defined
in the hardware.

Regards,

Arjen
0 Kudos
Reply