Fortran 函数中的别名
出于优化原因,Fortran 强制子例程或函数的虚拟参数不是别名,即它们不指向相同的内存位置。
我想知道相同的约束是否适用于函数的返回值。 换句话说,对于给定的 myfunc 函数:
function myfunc(a)
real, intent(in) :: a(:)
real :: myfunc(size(a))
myfunc = a * 2
end function myfunc
这样写是否符合标准: a = myfunc(a) 和 b = myfunc(a) ?
For optimisation reasons, Fortran enforces that the dummy arguments of a subroutine or function are not alias, i.e., they do not point the the same memory place.
I am wondering if the same constraint applies to the returned value of a function.
In other words, for a given myfunc function:
function myfunc(a)
real, intent(in) :: a(:)
real :: myfunc(size(a))
myfunc = a * 2
end function myfunc
is it standard-compliant to write:
a = myfunc(a)
and
b = myfunc(a) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数的参数和函数的返回值是不同的东西。与前面的答案相反,函数参数是通过引用或通过复制输入复制输出传递的,除非它们使用
VALUE
属性声明为虚拟参数。这是 Fortran 与 C 的主要区别。但是,如果函数值是通过正常赋值 (=) 而不是通过指针赋值 (=>) 构造的,则它们是单独的实体。在您的代码中,myfunc 的值是通过复制 a 的值获得的。因此,
a = myfunc(a)
或b = myfunc(a)
不会违反任何标准规则。The arguments of a function and function return value are different things. Contrary the previous answer, the functional arguments ARE passed by reference, or by copy-in copy-out, unless they are declared as dummy arguments with the
VALUE
attribute. This is a major difference of Fortran vs. C.However, if the function value is constructed by normal assignment (=) and not by pointer assignment (=>) they are separate entities. In your code, the value of myfunc is got by copying the value of a. Therefore no standard rules are broken by
a = myfunc(a)
orb = myfunc(a)
.由于 myfunc 中的变量 a 是与从父例程作为虚拟参数传递的 a 分开的实体,因此完全可以这样做:
or
这里没有冲突,因为 a 的值被复制到内部的虚拟参数函数,函数被求值,最后函数的值被复制到a。
来自 Fortran 2008 标准草案:
一般来说,最好强制函数不产生副作用,例如使用
PURE
属性并为所有虚拟参数声明INTENT
。Since the variable a in myfunc is a separate entity from a that is being passes as a dummy argument from the parent routine, it is perfectly fine to do:
or
There is no conflict here because value of a is being copied to the dummy argument inside the function, the function is being evaluated, and in the end the value of the function is being copied to a.
From Fortran 2008 Standard draft:
In general, it is good practice to force functions to not have side-effects, e.g. use
PURE
attribute and declareINTENT
for all dummy arguments.