Nordico
Nordico

Reputation: 1307

Why one can't initialize INTENT(OUT) or RESULT variables in Fortran?

Gfortran won't let me compile the following code because nLines and nIOstts can't be initialized like this; so I had to declare them first and then add two lines to the code to set their required initial values.

Why does this work like this? Perhaps with INTENT(OUT) it makes a little more sense since the variable in which the function will store the data already exists (and I don't recall right now whether Fortran subroutines worked by reference or not), but for the RESULT variable it would seem rather unnecessary. Is this specific of the compiler or is it a general Fortran characteristic?

FUNCTION LinesInFile(nUnit,nIOstts) RESULT(nLines)

IMPLICIT NONE  
INTEGER,INTENT(IN)  :: nUnit  
INTEGER,INTENT(OUT) :: nIOstts=0  
INTEGER             :: nLines=-1

DO WHILE (nIOstts.EQ.0)  

    READ(UNIT=nUnit,FMT='(A)',nIOstts)
    nLines=nLines+1

ENDDO

END FUNCTION

Upvotes: 1

Views: 1052

Answers (1)

janneb
janneb

Reputation: 37248


TYPENAME :: variable = somevalue

doesn't do what you think it does. Namely, this will put an implicit SAVE attribute on the variable, with the initial value somevalue. SAVE doesn't make sense for procedure arguments, hence it's not allowed.

So what you want is


TYPENAME :: variable
variable = somevalue

which will set the value to somevalue every time when the procedure is executed.

Upvotes: 10

Related Questions