Search code examples
arraysiofortran

In FORTRAN, what is the use of FMT without parameters?


I check an old FORTRAN 77 program.
It has an FMT character array, lets say:

CHARACTER*4 FMT(4)

which gets some elements like:

/'9,','1X','A','0'/ ...etc...  

During execution, FMT elements might get different values e.g.:

FMT(4) = '3x'

I m confused because the WRITE statement is like this

WRITE (xOUT,FMT) 'Result: ',(trek(j),j=1,Nev)

The FMT is an array. Right ? Not a string.
So what FORMAT exactly will the WRITE read from FMT ?
Any help is much appreciated.


Solution

  • The variable FMT is a character array. When an array is used as the format of an input/output statement, it is treated as though (Fortran 2018, 13.2.2 p3) each element is specified and concatenated. So in this case

    write(xOUT,FMT) ...
    

    is interpreted like

    write(xOUT,FMT(1)//FMT(2)//FMT(3)//FMT(4)) ...
    

    Which is unfortunate, because FMT(1) must have a ( as its first non-blank character.

    Outside a character edit descriptor blanks in a format are not significant.


    This, although it initially seems odd, is a handy way to create dynamic formats. Consider an extreme example where we want to write a string used as a format which could be (I5.5) or (F26.14).

    This could be:

    character(6) fmt(3)
    fmt(1) = '('
    fmt(3) = ')'
    
    if (something) then
      fmt(2) = 'I5.5'
      print fmt, 113
    else
      fmt(2) = 'F26.14'
      print fmt, 123.56
    end if
    

    (Yes, you wouldn't do this, I hope, but one can easily extend this to situations where it does seem appealing.)

    Compare with

    character(8) fmt
    fmt = '(      )'
    
    if (something) then
      fmt(2:7) = 'I5.5'
      print fmt, 113
    else
      fmt(2:7) = 'F26.14'
      print fmt, 123.56
    end if
    

    to see what the author was trying to avoid.