我们还需要子程序吗? [英] Do we still need subroutines?

查看:168
本文介绍了我们还需要子程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Fortran中,函数和子例程之间存在明显的区别:函数返回一个值,子例程不返回任何值。这引出了两者之间的一系列差异。一个例子是调用语义:您可以像调用其他语言一样调用函数,但为了调用子例程,您必须首先发出调用语句。



在Fortran95中添加指针和数据类型后,似乎没有任何技术限制使得任何子程序成为一个函数,并且保留子程序仅用于遗留。函数可以返回零(你只是返回一个虚拟整数),一个或多个值(例如,你可以返回一个指向一个类型的已分配实例的指针,例如C ++ STL Pair)。



我错了吗?我们是否仍然需要Fortran编程中的子程序,这是因为子程序具有和功能不具备的某些功能?解析方案

如果您搜索comp.lang.fortran档案,你会发现关于函数语义的讨论。 IIRC事实证明,在标准中没有明确规定什么是和什么是不允许有副作用的功能。例如,编译器是否可以优化

x = foo(args)+ foo(args) p>

转换为



x = 2 * foo(args)

<例如,考虑如果foo(f)(y) b

)改变y的值?请记住,Fortran没有C语言的序列点概念。

一般来说,几位专家的建议是只在函数纯时使用函数,否则使用子例程。而且,这也是我关注自己的建议。


In Fortran, a clear difference exists between function and subroutine: functions return one value, subroutines return no value. This introduce a cascade of differences between the two. One example is the calling semantics: you can call a function just as in other languages, but in order to call a subroutine you must issue a call statement first.

With the addition of pointers and data types in Fortran95, it appears that there is no technical limitation in making any subprogram a function, and keeping subroutines just for legacy. Functions could return zero (you just return a dummy integer), one, or multiple values (for example, you could return a pointer to an allocated instance of a type, like a C++ STL Pair).

Am I wrong? Do we still need subroutines in Fortran programming due to some feature that subroutines have and functions don't?

解决方案

If you search the comp.lang.fortran archives, you'll find discussions about the semantics of functions. IIRC it turns out that it's not clearly specified in the standard what is and what isn't allowed for functions that have side-effects.

For instance, can the compiler optimize

x = foo(args) + foo(args)

into

x = 2 * foo(args)

Or for another example, consider

x = y + foo(y)

What if foo() changes the value of y? Remember that Fortran doesn't have the C concept of sequence points.

In general, the recommendation by several experts is to use functions only if they're pure, otherwise use subroutines. And, that is advice that I follow myself as well.

这篇关于我们还需要子程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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