Variable format in Fortran 90
In Fortran there are nowadays many ways to write formatted output. In the following example, the same output may be given in 5 ways. The last two examples include a version of format that may include a variable:
program Console1
implicit none
integer(4)::i,num
character(50)::f
i=4;num=2;
!#1 (old)
print 10,i,i
10 format(2I3)
!#2
print '(2I3)',i,i
!#3
f='(2I3)'
print f,i,i
!#4
!convert from number to character and write to f
write(f,'(I4)') num
f='(' // trim(f) // 'I3)'
print f,i,i
!#5 (Intel compiler specific)
print '(<num>I3)', i,i
end program Console1
Comments
Also, as far as I'm concerned we should not even remind people of #1. Label statements are terrible and remind me of the bad old days of unstructured programming and GOTO statements. It is much better to use character constants or variables to construct edit descriptors, and this can be done dynamically as you have demonstrated.
Whatever we write using the print statement, we can write using the write statement of course, so we can use, instead:
f='(I4)'
write(*,f) i