Lelouch
Lelouch

Reputation: 2193

Fortran unassigned array

I just begin learning Fortran, and I come across this issue. Consider the following simple code.

PROGRAM random

INTEGER, DIMENSION(12):: array
PRINT *, array

END PROGRAM random

The array is not assigned value, but can be printed, and it seems to have a few random elements and several zero elements. However, if I consider a shorter array, say I declare

INTEGER, DIMENSION(5):: array

then the printed array has all elements = 0. I wonder what is happening here?

Upvotes: 4

Views: 742

Answers (2)

casey
casey

Reputation: 6915

If you do not initialize the variable you are seeing whatever happens to be in the memory that your variable occupies. To initialize your array to 0, use the statement:

integer, dimension(12) :: array
array = 0

If you do not initialize your variable before accessing it, your are using undefined behavior and your program is invalid.

Upvotes: 4

Madhurjya
Madhurjya

Reputation: 507

When you define an array and try to look at the values it contains (i.e. by printing) before initialising it, the behaviour is undefined. It depends on compiler to compiler. While one compiler may automatically set all the values to zero (which many of us think that to be the default), another compiler may set it to completely random values. Which is why you are seeing the array values sometimes zero and sometimes not.

However, many of the compilers have options to initialise an unassigned array to zeros at compiler level. It is always advised that one should initialise an array always before using it!

Upvotes: 6

Related Questions