L5RK
L5RK

Reputation: 109

How to set Fortran Integer kind

program PEU3
integer(kind=7) :: num = 600851475143
integer(kind=7) :: pf, counter 

This is a section of my fortran code. Num is very large, so I tried to set it to kind = 7, but for some reason It's still throwing Error 217 - Integer(Kind=3) Constant out of range, for the line declaring num, even though I've declared that num ought to be kind 7. I've been at it for a while and can't understand for the life of me why it wouldn't be working. Help would be greatly appreciated. My IDE is Plato, with silverfrost compiler, if it's relevant.

Upvotes: 1

Views: 2377

Answers (1)

chw21
chw21

Reputation: 8140

Notice how the error is "Constant out of range", not "Variable out of range". The Constant in the line

integer(kind=7) :: num = 600851475143

is the actual number: 600851475143. By default, your compiler seems to want to store constants as 32 bit integers, and that number is too large for that.

The simplest solution would be to tell the compiler to store that constant as the same kind as the num, so something along these lines:

integer(kind=7) :: num = 600851475143_7

That trailing underscore tells the compiler to store the constant as an integer of kind 7.

BUT

I need to point out that what number corresponds to which kind is compiler and machine dependent. Which means like that, the code would not be easily transferable.

So please use one of these constructs:

For newer compilers (Fortran 2008 compliant), use the intrinsic iso_fortran_env module:

program PEU3
    use iso_fortran_env, only: int64
    implicit none
    integer(kind=int64) :: num = 600851475143_int64

For older compilers, you can use the selected_int_kind method to find out the best integer kind. It takes a single parameter: The maximum number of (base 10) digits to store. (Though technically, if you pass it the number 12, it would only guarantee the numbers between -10^12 ... 10^12, so you'd have to pass 13 to be certain that your number can be stored.)

integer, parameter :: largeint = selected_int_kind(13)
integer(kind=largeint) :: num = 600851475143_largeint

Both of these methods are more easily readable and compiler-independent, so much easier to port to a new system.

Upvotes: 6

Related Questions