1.5.6 Dynamic Changes to Format

When using the FORMAT statement to specify the format of output with WRITE statements, one cannot "judge the number of necessary digits in the program and change the number of digits of the output," since variables cannot be used in the format. This is one of the inflexible characteristics of an old language, but we urge you to read the explanation below before crying, "That's why I hate FORTRAN."

In FORTRAN77, the character variable can be specified instead of the number of the FORTRAN statement as the format identifier of the WRITE statement. It is possible to make dynamic changes to format using this function.

      CHARACTER CFMT*12

      ...

      CFMT = '(T12, F5.2)'

      WRITE(6,CFMT) X

      ...

In this example, a constant is simply assigned to the character variable CFMT, so the format is not designed to be changed dynamically, but since CFMT is a variable, it can be easily changed in the program.

The WRITE statement is used to write numerical variables such as the number of digits into the character variable.  By writing the character variable in place of the output device number in the WRITE statement, it is possible to make the program treat the character variable as an "internal file," and just like a normal WRITE statement, it can be edited and outputted.

      CHARACTER CFMT*12

      ...

      CFMT = '(T12, Fx.2)'

      WRITE(CFMT(8:8),'(I1)') N

      WRITE(6,CFMT) X

      ...

In this example, an integer variable N is written into the line 8 of the character variable CFMT, to designated it as the number of digits when outputting X. This technique could not be used in FORTRAN66, so it is not widely known, but it is extremely convenient.