将内联字符串传递给参数已定义长度的子例程调用会产生意外的结果 [英] Passing a string inline to a subroutine call, where the parameter has defined length, gives unexpected results

查看:117
本文介绍了将内联字符串传递给参数已定义长度的子例程调用会产生意外的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个代码意外行为

  module testmodule 
integer,parameter :: LCHARS = 50
包含
子程序init()
调用foobar(foobar)
结束子程序

子程序foobar(s)
字符(len = * ),intent(in):: s
调用栏
结束子程序

子程序栏(str)
字符(len = LCHARS),intent( in):: str

print *,str
结束子程序
结束模块

程序foo
使用testmodule
调用init()
结束程序

这段代码输出依赖于编译器的垃圾。



我发现问题在于我正在跳过一个例程,其中 len = * 用于一个字符串参数,它是然后传递给具有指定长度的字符串参数的例程。



到底是什么发生了什么,标准中的这个行为是d旁切?我应该避免为字符例程参数指定长度,因为这种行为可能在任何时候都会发生,而无需警告?解决方案

我认为你的代码不符合。 Fortran 95标准的部分 12.4.1.1 指出:


12.4 .1.1与虚拟数据对象关联的实际参数

[...]

如果标量虚拟参数的类型为默认字符,则长度 len 的伪参数
应小于或等于实际参数的长度。伪参数变为与实际参数的最左端的 len 字符关联的



I found this code to behave unexpectedly

module testmodule
   integer, parameter :: LCHARS = 50
contains
   subroutine init()
      call foobar("foobar")
   end subroutine

   subroutine foobar(s)
      character(len=*), intent(in) :: s
      call bar(s)
   end subroutine

   subroutine bar(str)
      character(len=LCHARS), intent(in)  :: str

      print *, str
   end subroutine
end module

program foo
   use testmodule
   call init()
end program

This code prints garbage which is compiler dependent.

I see the problem being the fact that I am jumping through a routine with len=* for a string argument, which is then passed to a routine with specified length for the string argument.

What's going on exactly under the hood, and where in the standard is this behavior described? Should I refrain from having specified length for character routine arguments, since this behavior may happen at any time without warning?

解决方案

I think your code is non-conforming. Section 12.4.1.1 of the Fortran 95 standard states:

12.4.1.1 Actual arguments associated with dummy data objects
[...]
If a scalar dummy argument is of type default character, the length len of the dummy argument shall be less than or equal to the length of the actual argument. The dummy argument becomes associated with the leftmost len characters of the actual argument.

这篇关于将内联字符串传递给参数已定义长度的子例程调用会产生意外的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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