bcf
bcf

Reputation: 2134

Specify Integer Precision gfortran

I'm working with integers larger than 2^31-1 and so I'm trying to set the precision of my integer variables to a higher value. The method I thought was correct was

PROGRAM f1
IMPLICIT NONE

INTEGER,PARAMETER :: LONG = SELECTED_INT_KIND(15)
INTEGER(KIND=LONG) :: n
n=2**31

END PROGRAM f1

which, as I understand, should allow n to be in [-10^15, 10^15]. However the above code throws a compiler error using gfortran 4.6, namely

n=2**31
   1
Error: Arithmetic overflow at (1)

I've tried replacing the trouble line with n=int8(2**31) but to no avail. Any recommendations?

Upvotes: 1

Views: 165

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78316

This is a near-duplicate of this recent question so I should probably vote to close but here goes, again

In the expression 2**31 both 2 and 31 are default integers, most likely 32-bit integers. The compiler will multiply them according to the rules for 32-bit integers, and overflow, before assigning the result to n. If this is not the behaviour you want either fiddle with the compiler options (bad recommendation) or clearly set the kind for the literal values (better):

n = 2_long**31_long

(In practice you don't need to make both 2 and 31 long integers but it does no harm.)

Upvotes: 2

Related Questions