Function returning string - cannot write result

Hello,

I have a problem trying to WRITE the result of a function that returns a string. Whenever I try to WRITE the result, I get an error: “PGFIO-F-235/formatted write/internal file/edit descriptor does not match item.” However, if I try PRINT, the result is displayed correctly.

PROGRAM test
   CHARACTER(LEN=4)      :: mambo  !function
   INTEGER                       :: x

   x = 1
   WRITE(*, '(A)') mambo (x)
END PROGRAM test

FUNCTION mambo (x) RESULT (string)
   CHARACTER(LEN=4)        :: string
   INTEGER                         :: x

   WRITE(string, "(I4.4)") x
   RETURN
END FUNCTION mambo

Since x = 1, I would expect the program to print out ‘0001’. Instead, I get:

inferno [1739] ./a.out
PGFIO-F-235/formatted write/internal file/edit descriptor does not match item

If I replace “WRITE(*, ‘(A)’) mambo (x)” with “PRINT *, mambo(x)” … it works as expected.

Any idea what is going on?

Thanks

Hi mwhite,

The statement “WRITE(*, ‘(A)’) mambo (x)” is illegal F95 since mambo contains an WRITE statement. Functions that are part of an output list may not cause execution of another input/output statement. You’ll need to create a temporary variable to hold the return value. I believe this restriction has been lifted in the F2003 standard.

  • Mat

Example:

% cat mambo.f90
PROGRAM test
   INTEGER                       :: x
   character(len=4) :: temp
   character(len=4) :: mambo

   x = 1
   temp =  mambo(x)
   WRITE(*, '(A)') temp
END PROGRAM test

FUNCTION mambo (x) result(string)
   CHARACTER(LEN=4)        :: string
   INTEGER                 :: x
   WRITE(string, '(I4.4)') x
   RETURN
END FUNCTION mambo

% pgf90 mambo.f90
% a.out
0001

Ah, thanks for the explanation, Mat. Your suggested fix worked perfectly.