Fortran中intent的用法

Fortran中intent的用法

以下内容中将function和subroutine统称为函数块

和C不同,Fortran在向函数块传递参数时并非值传递,而是地址传递,因此在函数块内修改变量的值会使得主调函数中的变量的值也发生改变,因此有时我们需要将形参声明为只读,以保证主调函数端的变量值不发生改变.这时就需要用到intent关键字.intent用于修饰形参的属性,常在函数块中定义(声明)形参时出现,形参的属性可声明为以下三种:

  • intent(in) 将变量声明为只读,若在函数块中修改了其值,编译时会报错
  • intent(out) 将变量指定为要输出的变量,若在函数块中没有赋一个新的值给它,则编译时会报错
  • intent(inout) 将变量声明为可读可写的变量,当intent缺省时默认为intent(inout)

用法示例:

subroutine example(a, b, c, d)
	integer, intent(in) :: a
	integer, intent(out) :: b
	integer, intent(inout) :: c
	integer d !默认为intent(inout)
	....
	do some work
	...
end subroutine example
posted @ 2022-06-28 16:35  yukina~  阅读(4511)  评论(0编辑  收藏  举报