How to initialize array of integer kind 8 in fortran?

3.8k views Asked by At

I want to initialize an array of large integers in fortran, I have tried:

integer(kind=8) :: XGrid(1:20)

But the integers remain the default kind=4. As I later add numbers to the array:

XGrid = (/3002, 3340403,....,19460630000/)

And I receive a "This numeric constant is out of range" error. As it wont fit in a kind=4 int, but will in a kind=8 int.

I have also tried declaring it as:

integer, parameter :: ik8 = selected_int_kind(8) 
integer(ik8) :: XGrid(1:20)

But this also did not work.

Edit: Thanks Vladimir F, but I am trying to define an array rather than just a single variable and as such I cant understand how to adapt the answer used in: Is There a Better Double-Precision Assignment in Fortran 90? Would it be:

integer, parameter :: ik8 = selected_int_kind(8) 
integer(ik8) :: XGrid(1:20)_ik8
XGrid = (/3002_ik8, 3340403_ik8,....,19460630000_ik8/)

or is it different? Thanks

2

There are 2 answers

3
Vladimir F Героям слава On BEST ANSWER

First, kind=8 can be anything, it does not have to be 64-bit. Much better to use int64 from iso_fortran_env instead. You can make your own named constant named for example

integer, parameter :: ìp = int64

But more importantly,

(/3002, 3340403,....,19460630000/)

is a default integer array expression there is no information available to make it kind 8. What is before the = assignment is irrelevant. An expression does not care about its context. Se also Is There a Better Double-Precision Assignment in Fortran 90?

You must indicate the kind

(/3002_8, 3340403_8,....,19460630000_8/)

or better

(/3002_int64, 3340403_int64,....,19460630000_int64/)

(or _ip)

Fortran 2003 also allows to define the type of an array constructor

 [ integer(int64) :: ]

but that will not help here, each individual constant in the expression must be legal.

0
Matt P On

In addition to specifying the KIND for each value in the array (as shown by @Vladimir), you may be able to use a compiler option so that by default any integers with unspecified KIND will be 8 bytes long.

For example, with Intel Fortran on Windows it is: /integer-size:64, or Linux: -integer-size 64.

I haven't tried it, but there seems to be a similar option in gfortran: -fdefault-integer-8