4

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?

M. S. B.
  • 28,968
  • 2
  • 46
  • 73
Lelouch
  • 2,111
  • 2
  • 23
  • 33

2 Answers2

6

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!

Madhurjya
  • 497
  • 5
  • 17
4

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.

casey
  • 6,855
  • 1
  • 24
  • 37
  • But why don't the random elements show up until the length is greater than 8? – Lelouch Jul 25 '14 at 04:16
  • 1
    @Lelouch luck? There is no guarantee as to the contents of your array before you initialize it, and it is undefined behavior if you use the values in the array before initialization. – casey Jul 25 '14 at 05:07