Mistakes that will surprise you: the end-of-line backslash

I apologize in advance for the rant :slight_smile:
But I’ve just found out after hours of debugging that this program:

program t
   implicit none
   real :: A

   ! Just a comment \
   A = 2.0   
   print *, A

end

Will return garbage in A if compiled with gfortran -cpp or .F90.
The reason (I’ve now found) is that line A = 2.0 is not parsed by gfortran because of the tiny \ at the end of the previous comment line… so A=2.0 is treated as a continuation of the comment line. LOL!
Compiler explorer.

7 Likes

The question is now: why on earth did you put a backslash at the end of that comment? :grin:

1 Like

I’ve got literally no idea… it was some code I had ported from Matlab a while ago and for some reason I had a backslash at the end of the comment!!

1 Like

The backslash is quite useful when defining long macros with the pre-processor. If you don’t want C-like pre-processing, name the file with .f90 rather than .F90.

2 Likes

It works with ifx and ifort (with the -fpp flag). Can’t this be considered a bug? How should this affect the tentative F202y preprocessor?

Nope because it’s specific to the C Preprocessor: it’s its continuation character and apparently works anywhere, not just when continuing macro lines

1 Like

I wonder if the behavior is described in the flang preprocessor document: Fortran Preprocessing — The Flang Compiler

flang-new in the Compiler explorer returns the correct result, so it does appear that they’ve restricted its application to macro definition and other preprocessor-specific lines

Trying to integrate a subset of the C preprocessing has always been fraught with problems. Different compilers implement subtly different subsets. It gets really fun when one has to do multiple pre-processing passes. (ESMF does this for some files where macros are used for generating multiple versions of a code for different data types/kinds. We finally had to add our own utility function to concatenate character strings, because using the // operator was unreliable.)

Unless it is some really simple conditional compilation, I generally use fypp these days.

2 Likes

In my mind, \ should be interpreted as a continuation only on preprocessor directives in the F202y preprocessor standard. But that is just my opinion.

1 Like