在书籍中搜索了一段时间后,在这里有关于stackoverflow的文章,也有关于一般网络的文章,我发现很难找到对fortran参数意图之间真正差异的简单解释。我了解的方式是这样的:


intent(in)-实际参数在条目处复制到虚拟参数。
intent(out)-虚拟参数指向实际参数(它们都指向内存中的同一位置)。
intent(inout)-虚拟参数在本地创建,然后在过程完成时复制到实际参数。


如果我的理解是正确的,那么我也想知道为什么有人要使用intent(out),因为intent(inout)需要更少的工作(无需复制数据)。

最佳答案

意图只是对编译器的提示,您可以丢弃该信息并违反它。意图几乎完全存在,以确保您仅执行计划在子例程中执行的操作。编译器可能会选择信任您并优化某些内容。

这意味着intent(in)不能按值传递。您仍然可以覆盖原始值。

program xxxx
    integer i
    i = 9
    call sub(i)
    print*,i ! will print 7 on all compilers I checked
end
subroutine sub(i)
    integer,intent(in) :: i
    call sub2(i)
end
subroutine sub2(i)
    implicit none
    integer i
    i = 7  ! This works since the "intent" information was lost.
end

program xxxx
    integer i
    i = 9
    call sub(i)
end
subroutine sub(i)
    integer,intent(out) :: i
    call sub2(i)
end
subroutine sub2(i)
    implicit none
    integer i
    print*,i ! will print 9 on all compilers I checked, even though intent was "out" above.
end

关于arguments - fortran意图(in,out,inout)之间的明显区别是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1011604/

10-12 04:16
查看更多