fortran - 在未传递时使用带有 value 属性的可选参数
问题描述
我想使用带有属性“值”的函数参数。它是一个可选参数,我想在它没有被传递时使用它。我希望有一个与可选参数关联的局部变量,因为可选参数是按值传递的,而不是按引用传递的。但是当我尝试这样做时会发生奇怪的事情。
在下面的示例中,应该打印字符串“Hello”,但字符参数“Str”的内容似乎为空。
module test_value_mod
implicit none
contains
subroutine printStr(Str, AddTip)
! Declaration of parameters
character(len=*), intent(in) :: Str
logical, optional, value :: AddTip
if (.not. present(AddTip)) AddTip = .False.
write (*,*) 'Str: ', Str
if (AddTip) write (*,*) 'Tip is printed.'
end subroutine printStr
end module test_value_mod
program test_value_prog
use test_value_mod
implicit none
call printStr('Hello')
end program test_value_prog
但是,当我将字符长度作为另一个参数传递时,没有问题:
module test_value_mod
implicit none
contains
subroutine printStr(Str, LenStr, AddTip)
! Declaration of parameters
integer, intent(in) :: LenStr
character(len=LenStr), intent(in) :: Str
logical, optional, value :: AddTip
if (.not. present(AddTip)) AddTip = .False.
write (*,*) 'Str: ', Str
if (AddTip) write (*,*) 'Tip is printed.'
end subroutine printStr
end module test_value_mod
program test_value_prog
use test_value_mod
implicit none
call printStr('Hello', len_trim('Hello'))
end program test_value_prog
我使用 gfortran 7.3.0。但是,如果我使用 ifort 17.0.4 进行编译,对于上面给出的两个示例,我会收到以下错误:
forrtl: severe (174): SIGSEGV, segmentation fault occurred
Image PC Routine Line Source
test_value_passin 0000000000402C64 Unknown Unknown Unknown
libpthread-2.17.s 00007EFDA90825E0 Unknown Unknown Unknown
test_value_passin 000000000040288D test_value_mod_mp 15 test_value_passing.f08
test_value_passin 0000000000402A08 MAIN__ 29 test_value_passing.f08
test_value_passin 00000000004027CE Unknown Unknown Unknown
libc-2.17.so 00007EFDA8CD1C05 __libc_start_main Unknown Unknown
test_value_passin 00000000004026E9 Unknown Unknown Unknown
“test_value_mod_mp”中的第 15 行是:if (.not.present(AddTip)) AddTip = .False。
因此,我认为在实际未提供时使用按值传递的可选参数是无效的。但是,gcc 允许这样做,只有在您提供另一个假定长度的字符类型的输入参数时才会失败。
有人可以澄清一下吗?
解决方案
推荐阅读
- bazel - 访问 bazel BUILD 文件中的运行文件路径
- hyperledger - Hyperledger Indy 错误:池与此地址空间上的其他池重叠
- excel - 使用VBA将行号插入单元格
- c++ - 使用主函数
- ios - 来自 Swift 代码的抗锯齿像素被 OpenCV 转换为不需要的黑色像素
- ios - 如何快速禁用特定视图(名为“sideV1”和“sideV2”)的touchesbegan功能?
- sql-server - 选择语句数据返回慢从特定月份开始
- rest - 使用restful api删除所有项目
- javascript - 鼠标向上或向下操作时范围滑块不排序?
- cmake - catkin_make 中的 cmake 版本与全局 cmake 版本不同?