Zeus
Zeus

Reputation: 1565

Fortran functions returning characters

I have a function that returns a character string. In Fortran there is a requirement that the length of the output s has to be defined and cannot be (len=*). I am not sure what problems I might get into when I call a function and the string is shorter or longer that the size declared in the function.

Function real_to_str_new  &
  (                       &
    r, fmt                &
  )                       &
    Result (s)

Real, Intent(in) :: r
Character (len=*), Intent(in) :: fmt

Character (len=65) :: s

Upvotes: 2

Views: 228

Answers (1)

francescalus
francescalus

Reputation: 32451

That there is a function result isn't very important, and the question follows rules of assignment.

In (intrinsic) assignment where you have variable = expr for character types, the rules 7.2.1.3, 10 are:

For an intrinsic assignment statement where the variable is of type character, the expr may have a different character length parameter in which case the conversion of expr to the length of the variable is as follows.

(1) If the length of the variable is less than that of expr, the value of expr is truncated from the right until it is the same length as the variable.

(2) If the length of the variable is greater than that of expr, the value of expr is extended on the right with blanks until it is the same length as the variable.

In this case expr (as the function result) has length parameter 65 and variable will have length parameter as declared (unless allocatable comes into play).

Upvotes: 3

Related Questions