j3-fortran / fortran_proposals

Proposals for the Fortran Standard Committee
178 stars 15 forks source link

Syntax to initialize variables in declarations without SAVE #234

Open Beliavsky opened 3 years ago

Beliavsky commented 3 years ago

It is convenient to give a variable a value at the time it is declared, but in a procedure

integer :: i=0

has the implicit save attribute, which may not be wanted, and which many new Fortran programmers stumble over. I suggest adding an init attribute so that

integer, init :: i=0, j=1

has the same meaning as

integer :: i,j
i = 0
j = 1

Then the programmer can set the value of a variable in a declaration with the init, save, or parameter attribute, depending on the desired behavior.

certik commented 3 years ago

This is a duplicate of https://github.com/j3-fortran/fortran_proposals/issues/40#issuecomment-553520071, but keep it here as a top level issue, so that it is not buried in comments. However, every body please do read all the comments there, so that we do not repeat the discussion.

Other relevant issues:

klausler commented 2 years ago

What I took away from all of that discussion is that something like this, as an executable part statement, would answer all of the needs that were expressed:

let-stmt ::= LET [, let-attr-list ] :: let-init-list
let-attr ::= IMMUTABLE | TYPE(type-spec) | POINTER
let-init ::= object-name [ ( array-spec ) } initialization

Note that initialization is required. The type would be inferred from the initializer if not explicit. There is no SAVE attribute possible, explicit or implicit. It's not a construct, so no end let is needed. Later object-names could refer to earlier ones in the same statement in their initializations. If IMMUTABLE, the object-name could not appear in a variable definition context.

This subsumes auto, init, immutability, and other proposals, and more or less replaces associate.

UPDATE: see https://github.com/j3-fortran/fortran_proposals/issues/279 for more detail on this idea