Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.

How to compute 2**31 in Fortran?

woshiwuxin
Novice
1,204 Views
Hi, all! How can I compute 2**31 in Fortran? I set 'integer(kind=8)::i', but there seems always an overflow!
The code:
[fortran]program ex
implicit none
integer(kind=8)::i

i=2**31-1
write(*,*) i
i=i+1
write(*,*) i
i=2**31
write(*,*) i

stop
end[/fortran]
The result:
[bash]xwu@mac:/tmp> ifort -m64 ex.f90 
xwu@mac:/tmp> ./a.out 
            2147483647
            2147483648
           -2147483648[/bash]
Here's another related question. Could the correct result be guaranteed,if I am doing arithmetic or comparison of different _kinds_ of integers? _kind_ means the number of bytes. It seems that integer is always singed in Fortran (Intel Fortran Compiler User and Reference Guides, Document Number: 304970-006US, page 174).
Thank you in advance!
0 Kudos
3 Replies
woshiwuxin
Novice
1,204 Views
The compiler option '-i8' is a workaround. Is there anything eles (in the code) can help?
0 Kudos
TimP
Honored Contributor III
1,204 Views
As the data type for evaluation of an expression is determined from its components, you may have meant 2_8**31 or equivalent. As both operands will be promoted to the wider type, that is the same as 2**31_8 or 2_8**31_8, or ishft(2_8,31) etc. Likewise 2_8**31 > 0 is the same as 2_8**31 > 0_8.
Of course, it's better form to define a parameter constant for the next kind bigger than 32-bit size which happens to be 8 in ifort and gfortran but could also work with compilers such as SilverFrost.
0 Kudos
woshiwuxin
Novice
1,204 Views
Thank you, Tim!
0 Kudos
Reply