Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
29271 Discussions

ifc 7.1: Is it possible for a function to return a String or Character Arrays?

vsbabu
Beginner
745 Views
Hi,

Pardon my Fortran ignorance; but is it possible to write a function that returns a String?

Essentially, I want the return value of the function to be a string;

eg:

Character(*) Function MyStringMaker(Something)

so that I can call it like:
print *, 'My function produced '//MyStringMaker(20)

I know how to get this value returned in argument list for the function like:
Integer Function MyStringMaker(Something, MyOutPutInThis).

This is probably a generic Fortran question rather than IFC specific.

Cheers
0 Kudos
3 Replies
Steven_L_Intel1
Employee
745 Views
Yes, it is possible in standard Fortran. Actually,

character*(*) function

is valid even in Fortran 77, but it requires that the function name be declared with a specific length in the caller.

In Fortran 90, you would need an explicit interface for the function, which would look something like this:

function MyStringMaker(Strlen) result
integer, intent(in) :: Strlen
character(len=Strlen) :: r
...

Read up on "specification expressions" in your Fortran manual. As I noted, an explicit interface to the function must be visible to the caller. Read up on those too.
0 Kudos
vsbabu
Beginner
745 Views
Got a sample going here -- works with a limit of 256.

PROGRAM FN_RETURN_STRING
IMPLICIT NONE
Character*256 MyFunc

PRINT *, 'My function returns ' // Trim(MyFunc())

END PROGRAM

FUNCTION MyFunc() RESULT(String)
Implicit None
Character(*) String
String = "Hello World"
Return
End

Thanks Steve! I need to try out the docs you've mentioned.

The function below works as well.

Character*(*) FUNCTION MyFunc()
Implicit None
MyFunc = "Hello World"
Return
End

Message Edited by vsbabu@gmail.com on 01-19-2005 11:40 AM

0 Kudos
Steven_L_Intel1
Employee
745 Views
Ok, but in both of those cases, the length is determined by how the function is declared in the caller. If you want the function length to be dependent on the arguments, you'll need the other method I described and an explicit interface.

I see you also asked this in comp.lang.fortran - I'm sure you'll get good responses there.
0 Kudos
Reply