Search code examples
fortran

Expansion of a repeat count within a format statement (in conjunction with an implied do-loop)


In the following code I was under the impression that a repeat count in a formatted write simply expanded the bracket to be repeated.

program main
   implicit none

   integer, parameter :: N = 5
   real a(N), ct(N)
   integer i

   a = [ ( 0.1 * i, i = 1, N ) ]
   ct = 10 * a
    
   write( *, "( 1x, i4, 2( 1x, e11.4 )       )" ) ( i, a(i), ct(i), i = 1, N )   ! METHOD 1
   write( *, * )
   write( *, "( 1x, i4, 1x, e11.4, 1x, e11.4 )" ) ( i, a(i), ct(i), i = 1, N )   ! METHOD 2

end program

However, putting the repeat count in fails (throws an error on some compilers, writes garbage on others). Writing the whole lot out explicitly without a repeat count is fine. The implied do-loop may or may not contribute to the problem.


Solution

  • The formats

    ( 1x, i4, 2( 1x, e11.4 )       )
    

    and

    ( 1x, i4, 1x, e11.4, 1x, e11.4 )
    

    are not equivalent. Expansion of the repeat count does not work in exactly this way.

    Yes, the group in the first is expanded to give something that looks like the second, but there is a big difference in how the format behaves when there are more items to be written than there are data edit descriptors. This is "format reversion".

    In the first format, format reversion (reached after writing the first three data items) moves the processing back to the ( 1x, e11.4 ) group. In the second, because there is no internal (...) group, reversion goes back to the start of the whole format.

    For format reversion to work as you expect in the first, you can add another (...) group:

    (( 1x, i4, 2( 1x, e11.4 )       ))