Fortran CHARACTER (LEN = *) only apply to dummy argument or PARAMETER

夙愿已清 提交于 2019-12-13 12:09:09

问题


I want to print the following output

*****
****
***
**
*

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

Then it return error:

 CHARACTER(LEN = *) :: new_star
                           1
Error: Entity with assumed character length at (1) must be a dummy argument or a PARAMETER

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?


回答1:


CHARACTER(*) declares an assumed length character object. That means the object takes its length ("assumes it") from something else.

  • In the case of a CHARACTER(*) declaration for a dummy argument, the length is assumed from the length of the actual argument.

  • In the case of a CHARACTER(*) constant (a PARAMETER), the length is assumed from the value given to the constant.

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.

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

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 :.



来源:https://stackoverflow.com/questions/25051108/fortran-character-len-only-apply-to-dummy-argument-or-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!