fortran中save的用法?
编了一段程序,想看看save的用法,两个程序基本一致,只是a和b的赋值方法不用,第一个子程序a和b先声明再赋值,第二个子程序a和b声明时直接赋初值,但是结果却不一样,如下,这是什么原因?
第一个程序:
program main
implicit none
call sub()
call sub()
call sub()
call sub()
end
subroutine sub()
implicit none
integer a,b
integer c
save a,b
a=1
b=2
c=a+b
a=c+1
b=c+2
write(,)a,b
end
运行结果:
4 5
4 5
4 5
4 5
第二个程序:
program main
implicit none
call sub()
call sub()
call sub()
call sub()
end
subroutine sub()
implicit none
integer::a=1
integer::b=2
integer c
save a,b
c=a+b
a=c+1
b=c+2
write(,)a,b
end
运行结果:
4 5
10 11
22 23
46 47
save的作用不就是保存子程序每次运行时变量的值,下次运行时直接调取吗?
是的,save属性的变量在下次调用函数时,依然保留上一次的值。
但是,第一段程序。你每次进入子程序,都手动让它重新变成了初值:a=1,b=2 。所以每次都一样。
第二段程序,虽然没有显式说明他们具有 save 属性。但在子程序中初始化的变量,则默认具有 save 属性。
integer :: a = 1
等同于:
integer , save :: a = 1
但不等于:
integer , save :: a
a = 1