Fortran CHARACTER(LEN = *)仅适用于哑变量或参数 [英] Fortran CHARACTER (LEN = *) only apply to dummy argument or PARAMETER
问题描述
我要打印以下输出
*****
****
***
**
*
使用递归子程序。我的代码如下:
using recursive subroutine. And my code is as follows:
PROGRAM PS
IMPLICIT NONE
CALL print_star(5, '*')
CONTAINS
RECURSIVE SUBROUTINE print_star(n, star)
INTEGER :: n
CHARACTER(LEN = *) :: star
CHARACTER(LEN = *) :: new_star
IF (n > 1) THEN
new_star = star // '*'
CALL print_star(n - 1, new_star)
END IF
print *, star
END SUBROUTINE print_star
END PROGRAM PS
然后返回错误:
CHARACTER(LEN = *) :: new_star
1
Error: Entity with assumed character length at (1) must be a dummy argument or a PARAMETER
如果我只是避免定义 new_star
,而只是 CALL
If I just avoid defining new_star
, and just CALL
CALL print_star(n - 1, star // '*')
那么程序按预期工作。
then the program works as expected. I wonder what the error is about and how to resolve it?
推荐答案
CHARACTER(*)声明一个假定的长度字符对象。
CHARACTER(*) declares an assumed length character object. That means the object takes its length ("assumes it") from something else.
-
在CHARACTER(*)的情况下,
In the case of a CHARACTER(*) declaration for a dummy argument, the length is assumed from the length of the actual argument.
在CHARACTER(*)常量的情况下(参数PARAMETER ),长度假定为给定常量的值。
In the case of a CHARACTER(*) constant (a PARAMETER), the length is assumed from the value given to the constant.
从语言概念的角度来看,没有什么你的变量 new_star
可以假设它的长度,在它被声明的点。导致您看到的错误消息的语言规则反映了这一点。
From a language concept point of view there is nothing that your variable new_star
can assume its length from, at the point at which it is declared. The language rules that result in the error message that you see reflect this.
但是你知道 new_star
需要在程序中给出逻辑 - 它需要比 star
dummy参数的长度多一个。因此您可以正确声明:
But you know what the length of new_star
needs to be given the logic later in your program - it needs to be one more than the length of the star
dummy argument. So you can declare it appropriately:
CHARACTER(LEN(star) + 1) :: new_star
作为替代,Fortran 2003引入了延迟长度字符对象。这些是可分配的或指针对象,其中长度是在分配或关联对象时指定的。它们使用:
的长度说明符声明。
As an alternative, Fortran 2003 introduces deferred length character objects. These are either allocatable or pointer objects, where the length is specified at the time the object is allocated or associated. They are declared using a length specifier of :
.
这篇关于Fortran CHARACTER(LEN = *)仅适用于哑变量或参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!