Fortran 意图(输入、输出、输入)之间的显式区别是什么? [英] What is the explicit difference between the fortran intents (in,out,inout)?

查看:30
本文介绍了Fortran 意图(输入、输出、输入)之间的显式区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在书籍、stackoverflow 和一般网络上搜索了一段时间后,我发现很难找到对 fortran 参数意图之间真正差异的直接解释.我的理解是这样的:

After searching for a while in books, here on stackoverflow and on the general web, I have found that it is difficult to find a straightforward explanation to the real differences between the fortran argument intents. The way I have understood it, is this:

  • intent(in) -- 实际参数被复制到入口处的虚拟参数中.
  • intent(out) -- 虚拟参数指向实际参数(它们都指向内存中的同一个位置).
  • intent(inout) -- 虚拟参数在本地创建,然后在过程完成时复制到实际参数.
  • intent(in) -- The actual argument is copied to the dummy argument at entry.
  • intent(out) -- The dummy argument points to the actual argument (they both point to the same place in memory).
  • intent(inout) -- the dummy argument is created locally, and then copied to the actual argument when the procedure is finished.

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

If my understanding is correct, then I also want to know why one ever wants to use intent(out), since the intent(inout) requires less work (no copying of data).

推荐答案

意图只是编译器的提示,您可以丢弃该信息并违反它.意图的存在几乎完全是为了确保你只做你计划在子程序中做的事情.编译器可能会选择信任您并优化某些内容.

Intents are just hints for the compiler, and you can throw that information away and violate it. Intents exists almost entirely to make sure that you only do what you planned to do in a subroutine. A compiler might choose to trust you and optimize something.

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

This means that intent(in) is not pass by value. You can still overwrite the original value.

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  

这篇关于Fortran 意图(输入、输出、输入)之间的显式区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆