如何强制编译器将意图解析为意图(inout) [英] How to force compiler to interpret omitted intent as intent(inout)
问题描述
这个问题与问题有关:如何检测子程序内部违反 intent(in)
的情况。但我还没有在相关问题中找到答案在被调用的子例程/函数中,强制Fortran中的intent(in)声明变量也是常量。
$ b
声明为 intent(in)
可以被另一个子程序/函数修改,但省略了意图声明。
例如:
模块测试
隐式无
包含
子程序fun1(x)
real(8),intent(in):: x
调用fun2(x)
结束子程序
子程序fun2(x)
real(8):: x
x = 10
结束子程序
结束模块
gfortran和ifort可以在没有任何错误/警告的情况下编译此代码。所以我的问题是:
- 是否可以禁止省略意图声明?
- 是否有可能强制Fortran编译器将省略的意图解释为
intent(inout)
?
两个答案都是NO。未指定的意图与所有其他意图是根本不同的。它与intent(inout)不同,因为你可以将一个不可定义的表达式传递给一个具有未指定意图的子例程。
在许多上下文中,不允许指定意图所有(程序参数,Fortran 95中的指针,...)
如果你想要求指定意图,你可以定义你的子程序为纯粹的
,但它的作用远不止于此。但这对你来说可能是正确的。它禁止任何副作用。
This question is connected to the problem: how to detect violation of intent(in)
inside subprograms. But I haven't found the answer in the related question Enforce intent(in) declared variables in Fortran as constant also in called subroutines/functions.
A variable which is declared as intent(in)
can be modified by another subprogram/function with omitted intent declaration.
For example:
module test
implicit none
contains
subroutine fun1(x)
real(8), intent(in)::x
call fun2(x)
end subroutine
subroutine fun2(x)
real(8) :: x
x = 10
end subroutine
end module
This code can be compiled without any errors/warnings by gfortran and ifort. So my questions are:
- Is it possible to forbid omitting intent declaration?
- Is it possible to force a Fortran compiler to interpret omitted intent as
intent(inout)
?
Both answers are NO. Unspecified intent is fundamentally different from all other intents. It is different from intent(inout), because you can pass a nondefinable expression to a subroutine with unspecified intent.
Also in many contexts it is not allowed to specify intent at all (procedure arguments, pointers in Fortran 95,...)
If you want to require specifying of intent, you may define your subroutine as pure
but it does much more than that. But it may be the right thing for you. It forbids any side-effects.
这篇关于如何强制编译器将意图解析为意图(inout)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!