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?
A dummy argument in a statement function definition is classified as a variable name. A given name can appear only once in a dummy argument list. The name of a variable that appears as a dummy argument in a statement function statement has a scope of the statement in which it appears.
8.168 LEN — Length of a character entity Description: Returns the length of a character string. If STRING is an array, the length of an element of STRING is returned. Note that STRING need not be defined when this intrinsic is invoked, since only the length, not the content, of STRING is needed.
Dummy argument is a Fortran specific term. It is what other languages call formal parameters or similar, i.e. it is the object that is called X and Y (in your case) and witch gets associated to an actual argument when the procedure is called.
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 :
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With