Fortran 分配声明和 SAVE 属性陷阱 [英] Fortran assignment on declaration and SAVE attribute gotcha

查看:14
本文介绍了Fortran 分配声明和 SAVE 属性陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 fortran 95 中,如果在声明时分配变量

整数 :: var = 0

相当于

整数,保存 :: var = 0

因此变量在例程执行后被保留(相当于C语言中的static)并且在再次调用时不会重新初始化.这种(恕我直言危险)行为背后的基本原理/技术问题是什么?

解决方案

我不认为这种行为背后有什么理由.

但据我所知,Stefano,您使用了错误的术语.在您的代码中没有赋值语句只有使用初始化表达式 (0) 进行的变量 (var) 初始化.

整数 :: var = 0 !类型声明初始化整数 :: 变量!类型声明变量 = 0 !任务

看来这只是委员会的设计决定.如果我们有这样的表达式(在类型声明语句中带有等号),它是初始化而不是赋值.并且在程序(而不是程序)执行期间初始化只发生一次.

但是,这样的决定可能有一些历史原因.看看 这个 线程.p>

今天这种行为是危险的,因为许多其他广泛使用的语言遵循关于初始化/赋值的另一种约定.

In fortran 95, if you assign a variable at declaration

integer :: var = 0

it is equivalent to

integer, save :: var = 0

and the variable is therefore preserved after routine execution (is equivalent to static in C speak) and does not get reinitialized when called again. What is the rationale/technical issue behind such (IMHO dangerous) behavior ?

解决方案

I don't think that there is some rationale behind such behavior.

But as far as I know, Stefano, you used wrong terminology. In your code there is no assignment statement only variable (var) initialization using initialization expression (0).

integer :: var = 0 ! type declaration & initialization

integer :: var ! type declaration
var = 0        ! assignment

So it seems that it was just committee design decision. If we have such expression (with equality sign in type declaration statement) it is initialization not assignment. And initialization takes place only once during program (and not procedures) execution.

However there might be some historical reasons for such decision. Take a look at this thread.

Today such behavior is dangerous because many other widely used languages follows another conventions about initialization/assignment.

这篇关于Fortran 分配声明和 SAVE 属性陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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