Reputation: 5505
I have the following array:
type bar
integer*4 :: high
integer*4 :: low
end type
type(bar), dimension(2000:2025, 12, 31, 0:23, 0:59) :: data
I have the following questions:
Which value will have by default high/low variables in each derived type variable of the array? I.E., are they initialized to 0 by default? Does this depend on compiler or it is enforced by the standard?
What if derived type and array are defined in a module? Does it change anything?
If I would like to initialize the whole array high/low values to -1? Which would be the simplest way to do it?
If this depends on compiler then I am using gfortran (gcc8).
Upvotes: 1
Views: 978
Reputation: 32431
There are two forms of initialization in Fortran: explicit and default initialization.
In the snippet provided there is no initialization of any form, so the array data
has no initial value (in part or in whole). The array and the components would be initially undefined.
Default initialization would look like
type bar
integer :: high = -1
integer :: low = -1
end type
and in such a case an object of that form would have initial values for those components unless explicit initialization overrides them
Explicit initialization for the object array
would look like
type(bar), ... :: array = expr
for a suitable (constant) expression expr
.
In your case, a scalar constant expression bar(-1,-1)
uses the default structure constructor to specify an object with components set to those values. This is a valid constant expression. The scalar expression is then used to set the value for each element of the array.
This would have the same effect as with the above default initialization, but more generally could provide other values, and we can provide (conformable) array expressions for the initial values.
Default and explicit initialization may occur in modules or elsewhere without changing the above.
As noted in Vladimir F's answer, using explicit initialization gives the initialized object the save
attribute. Default initialization does not.
Upvotes: 1
Reputation: 60078
There is no particular value guaranteed. The values are undefined. Your compiler might promise some particular value, but it is not portable.
It changes nothing at all.
The default component initialization
:
type bar
integer*4 :: high = -1
integer*4 :: low = -1
end type
for all variables of that type.
Or you can initialize the array only.
type(bar), dimension(2000:2025, 12, 31, 0:23, 0:59) :: data = bar(-1, -1)
Note that the usual gotchas apply, the variable is now implicitly save
. But if it is a module variable it does not change anything. If it is a procedure local variable, be careful.
Please note that the *4
for integers is not valid Fortran 90. It is not standard Fortran at all.
Upvotes: 1