Difference between intent(out) and intent(inout)

匿名 (未验证) 提交于 2019-12-03 01:22:02

问题:

According to the Fortran standard:

The INTENT (OUT) attribute for a nonpointer dummy argument specifies that the dummy argument becomes undefined on invocation of the procedure

However this simple code gives me 5 as output, so it seems the argument didn't become undefined at the start of the procedure (in this case a subroutine).

subroutine useless(a)   integer, intent(out) :: a   print *,a end subroutine useless  program test   integer :: n=5   call useless(n) end program test 

What am I getting wrong? It seems that intent(inout) and intent(out) are the same.

回答1:

intent(inout) and intent(out) are certainly not the same. You have noted why, although you don't draw the correct conclusion. On entering the subroutine useless a is undefined, rather than defined.

Having a variable "undefined" means that you cannot rely on a specific behaviour when you reference it. You observed that the variable a had a value 5 but this does not mean that the only value you could observe is 5. In particular "undefined" does not mean "takes a specific value like NaN".

Your code is not standard conforming because of this reference to an undefined variable. See Fortran 2008 6.2 (similar meaning will be somewhere in Fortran 90 as initially tagged). Of particular note is that the compiler doesn't have to point out your mistake.

With intent(inout) the variable a would be defined when referenced and it will be guaranteed to have the value 5 (for a conforming processor).

More widely, there are other differences between the two intent attributes and this "coincidental" appearance of the similarity of the definition of the variable a could be more troublesome.

Allocatable arrays and objects with deferred type parameters, for example, are deallocated; derived types become undefined (and any allocatable components deallocated) and components with default initialization are "re-initalized"; pointers have their association status become undefined.

All of these latter things have potential for very awkward results, much more so than with a scalar integer, if they are referenced without being defined first.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!