Fortran type conversions

2019-06-11 23:30发布

问题:

I have the following command to set my array

Use, Intrinsic :: iso_fortran_env
Integer (Int8), Allocatable :: iu(:)

Allocate (iu(4))
iu = [4,3,2,1]

How can I stop the compiler giving me

Allocate (iu(4));  iu = [4,3,2,1]
                       1
Warning: Possible change of value in conversion 
from INTEGER(4) to INTEGER(1) at (1) [-Wconversion]

回答1:

High Performance Mark's answer about solves your problem. However, assuming int8 isn't the default kind (which the error messages supports) each element in the array constructor given in that answer should have the same type (they have) and kind (they haven't) parameter. So:

iu = [4_int8,3_int8,2_int8,1_int8]

is a valid constructor which shouldn't involve conversion.

It's a bit tedious to do that, especially with many elements, so it's worth noting that (as described in Fortran 2008 4.8) it's possible to use a type specification in the array constructor to specify the type and type parameters of the array. You can, then, write

iu = [integer(Int8) :: 4, 3, 2, 1]

where the values need now only be conformable with integer(Int8).

Whether gfortran complains about conversion seems to depend on the compiler version. Testing with an old version there was still a warning, with 4.9.0 there wasn't.



回答2:

Try

iu = [4_int8,3,2,1]

But it is just a warning and the other way to stop the compiler would be to set or unset a flag. Since you're silent on which compiler you're using I won't guess what's in its documentation or what flag to set to what value.