Hi,
I have a simple question, but I can't figure out the answer. Does anyone know why the following program outputs b=-589934592 instead of b=8000000000 ? This must be related to the product of a*a*a causing an integer overflow. I want to have intermediate variables be integer(kind=4) and the result stored in integer(kind=8).
[fortran]
program test_integer8
implicit none
integer(kind=4) a
integer(kind=8) b
a = 2000
b = a*a*a ! How do you fix this line?
write(*,*) 'b = ', b
stop
end program test_integer8
[/fortran]
Roman
链接已复制
It would work, but I have a general distaste for mixed-mode arithmetic or assignments. I think it's clearer when you express conversions explicitly. (I would also discourage use of literals such as 8 for kind values - better to define PARAMETER constants using SELECTED_INT_KIND, etc.)
Thanks for the comments.
Steve, what is the reason you discourage literals for kind values? I like them because I immediately know how much memory will be needed. integer(kind=4) will need 4 bytes per variable, integer(kind=8) will need 8 bytes, etc. The only exception is when working with complex variables since complex(kind=8) will need 8*2=16 bytes. Is the problem that the kind values are not standard, and on a different platform might mean something different?
Roman
Roman wrote:
What is the reason you discourage literals for kind values?
Kind values are not portable between compilers. For example, the NAG compiler uses kind=1 for 32-bit reals and kind=2 for 64-bit reals (.i.e., double precision).
Exactly. I would also argue that in most cases you don't need to know how much storage is taken up - you just want to know what range of values you can store. In the circumstances where you do need to know the size, there are intrinsics such as STORAGE_SIZE and C_SIZEOF that can help you with that. The C interoperability features also define kind constants for specific sizes of integers and reals.
I don't know of current compilers that don't support that extension, but I would encourage you to use standard syntax where available and when writing new code. I don't recommend going back and changing existing code.