mgilson
mgilson

Reputation: 309841

fortran save integer

I came across some code today that looked somewhat like this:

      subroutine foo()
      real blah
      integer bar,k,i,j,ll
      integer :: n_called=1
      save integer

      ...
      end

It seems like the intent here was probably save n_called, but is that even a valid statment to save all integers -- or is it implicitly declaring a variable named integer and saving it?

Upvotes: 2

Views: 411

Answers (2)

Hristo Iliev
Hristo Iliev

Reputation: 74375

The second interpretation is correct. Fortran has many keywords, INTEGER being one of them, but it has no reserved words, which means that keywords can be used as identifiers, though this is usually a terrible idea (but nevertheless it carries on to C# where one can prefix a keyword with @ and use it as an identifier, right?)

The SAVE statement, even if it was intended for n_called is superficial. Fortran automatically saves all variables that have initialisers and that's why the code probably works as intended.

 integer :: n_called=1

Here n_called is automatically SAVE. This usually comes as a really bad surprise to C/C++ programmers forced to maintain/extend/create new Fortran code :)

Upvotes: 5

High Performance Mark
High Performance Mark

Reputation: 78316

I agree with your 2nd interpretation, that is, the statement save integer implicitly declares a variable called integer and gives it the save attribute. Fortran, of course, has no rule against using keywords as program entity names, though most sensible software developers do have such a rule.

If I try to compile your code snippet as you have presented it, my compiler (Intel Fortran) makes no complaint. If I insert implicit none at the right place it reports the error

This name does not have a type, and must have an explicit type.   [INTEGER]

The other interpretation, that it gives the save attribute to all integer variables, seems at odds with the language standards and it's not a variation that I've ever come across.

Upvotes: 3

Related Questions