Is it possible to convert Logical(4) to Integer(4)

5,109 views
Skip to first unread message

Ray

unread,
Jul 8, 2009, 6:41:51 PM7/8/09
to gg95
Hello:

I use g95 as my fortran compiler. I always get this kind of
error:

Can't convert LOGICAL(4) to INTEGER(4) at (1)
Can't convert INTEGER(4) to LOGICAL(4) at (1)

Are Logical and Integer variables convertible?

Thanks,
Ray

Evangelos Bertakis

unread,
Jul 9, 2009, 3:41:05 AM7/9/09
to gg...@googlegroups.com
Hello!

You probably have in your code something like this:
logical:: a=.true.
integer:: b=1
a=b
end

The fortran compiler can't automatically convert from integer to
boolean and visa versa. If you definitely need this, you have to do it
manually, like:
if (a) then
b=1
else
b=0
end if

Vangelis

Jimmy

unread,
Jul 9, 2009, 4:38:16 AM7/9/09
to gg...@googlegroups.com
Also, in the sense of storage, you can use the 'transfer' function, eg
program test
logical :: a
integer :: i,j
i=99
a=transfer(i,a)
j=transfer(a,j)
write(*,*)j
stop
end program test

Jimmy.

Ray

unread,
Jul 9, 2009, 10:31:36 AM7/9/09
to gg95
Thank you all. I will try.

Tobias Burnus

unread,
Jul 27, 2009, 4:57:42 AM7/27/09
to gg95, Tobias Burnus
On 9 Jul., 10:38, "Jimmy" <jh...@sky.com> wrote:
> Also, in the sense of storage, you can use the 'transfer' function, eg
>       program test
>       logical :: a
>       integer :: i,j
>       i=99
>       a=transfer(i,a)
>       j=transfer(a,j)

I want to add a warning: Especially with higher optimizations such as -
O2 or -O3 one can quickly run into problems. Some compilers regard the
highest or the lowest bit as relevant to decide whether a number
is .true. or .false. While false = "0" usually (always) works, other
number might not. With C, integers nonequal zero are true and zero
false - but also there, using the "bool" type, there might be problems
if not "true/false" is used by if an integer is casted.

The safest way to convert integers to logicals is: (i /= 0)
For logical -> integer, one can use TRANSFER, but one should not
expect a special number, .TRUE. might be -1 or 1 (or any other number,
so far I only encountered -1 and 1, though).

GCC is one of those compilers, where IF(TRANSFER(2,.true.)) is
regarded as false in high optimization levels. I do not know whether
it affects GCC 4.0.x as used by g95 nor how g95 handles logicals as
datatype internally - thus it may or may not effect g95. (And for the
example above: As this is compile-time evaluable, the result of the
transfer is presumably .TRUE. independent of the optimization level.)

Tobias
Reply all
Reply to author
Forward
0 new messages