Search code examples
iofortranintel-fortran

Fortran internal write suddenly an error according to Intel compiler


A Fortran code I am working on has several lines similar to

WRITE(filename, '(A16,"_",I4,".dat")') filename, indx

This code has been successfully compiled and run literally hundreds of times, on many different platforms and pretty much all major compilers. But suddenly the newest (or, new, anyway) Intel compiler doesn't like it. It gives a warning message "forrtl: .... Internal file write-to-self; undefined results". After this line executes, "filename", which was a reasonable character array, becomes blank.

I suppose the problem is that filename is both an input into the write and the destination of the internal write. The fix is easy enough. It works to replace filename as the destination with something like filename_tmp. But as I have said, this has never been necessary until now.

So I am wondering, does filename as both an input and destination violate the Fortran standard, but all these compilers have been turning a blind eye to it for all these years, and now Intel is getting strict? Or is Intel being "snobbish"? Or outright buggy?


Solution

  • Execution1 of the write statement of the question has always been explicitly prohibited.

    We currently see (F2018 12.6.4.5.1 p7):

    During the execution of an output statement that specifies an internal file, no part of that internal file shall be referenced, defined, or become undefined as the result of evaluating any output list item.

    filename is an internal file, and the evaluation of the output list item filename is a reference to that internal file.

    This is not a programming violation that the compiler is required to detect, so you can view this as a case of improved diagnostic capability/pickiness of the compiler as you desire. No Fortran program is harmed by the change in this behaviour of the compiler.

    Fortran 66 didn't have internal files (or character types), of course, and Fortrans 77, 90 and 95 used different words for the same effect (see for example, F90 9.4.4):

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

    In case it looks like this is more restrictive, from Fortran 2003 the restrictions for input and output statements are stated separately (only output was quoted above, p8 for input).


    1 Note the use of execution: there's nothing wrong with the statement itself as a statement. It is allowed to exist in source code that isn't reached. Checking this statement when compiling is not a simple matter.