Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
Announcements
Welcome to the Intel Community. If you get an answer you like, please mark it as an Accepted Solution to help others. Thank you!
26730 Discussions

issue with write from and to the same string

Uwe_H_
Beginner
108 Views

After updating from intel fortran 18.0.1 to 19.1.0 I noticed a difference when writing to a character variable. This is a minimum sample:

    program Console1

    implicit none
    character(20) :: line
    
    line = 'A'
    write(line, '(2(a,x))')line(1:1), 'B'
    write(line, '(2(a,x))')line(1:3), 'C'
    write(line, '(2(a,x))')line(1:5), 'D'    
    print *, line
    
    line = 'A'
    write(line, '(2(a,x))')trim(line), 'B'
    write(line, '(2(a,x))')trim(line), 'C'
    write(line, '(2(a,x))')trim(line), 'D'    
    print *, line

    end program Console1

Output with the "old" compiler:

 A B C D
 A B C D

... and with the new one:

       D
 A B C D

I verified this only happens when writing from and to the same variable, not if you use a copy. In the real code I changed it to the trim-approach which makes more sense to me anyway, but I´m still curious: Is this supposed to work like it did before, or is it "forbidden" to use the same variable here?

0 Kudos
4 Replies
mecej4
Black Belt
108 Views

Section 9.6.4.5.1 (note no. 6) of the Fortran 2015 standard says:

If an internal file has been specified, an input/output list item shall not be in the file or associated with the file.

When a program is not standard conforming, the behavior of the program is unpredictable. 

FortranFan
Honored Contributor II
108 Views

mecej4 wrote:

Section 9.6.4.5.1 (note no. 6) of the Fortran 2015 standard says:

If an internal file has been specified, an input/output list item shall not be in the file or associated with the file.

..

That appears to be from the Fortran 2008 standard.  By the way, there's no 2015 standard - there's a 2018 one.

Uwe_H_
Beginner
108 Views

Thanks for confirming this.

Btw. it turns out the "trim"-thing also does not work reliably, I guess other than what I expected it does not guarantee to make a copy. So I ended up doing something like

line = trim(line)//'B'

Performance is not an issue in this case.

FortranFan
Honored Contributor II
108 Views

Uwe H. wrote:

.. Performance is not an issue in this case.

Operations using IO statements such as WRITE to an internal file may not be all that performant anyway.

You may want to consider straightforward "string" operations that help with code readability as well

   character(len=*), parameter :: SPACE = " "
   character(len=:), allocatable :: line
   line = "A"
   line = line // SPACE // "B"
   line = line // SPACE // "C"
   line = line // SPACE // "D"
   print *, line
end

Upon execution,

 A B C D

 

Reply