Luke Davis
Luke Davis

Reputation: 2666

With fortran PGI compiler, why is real(.true.) equal to "-1.0" and int(.true.) equal to "-1"?

I just discovered this lovely fact. Evidently this is also true for Visual Basic... perhaps the answer is similar? And perhaps it applies to other languages as well?

Edit

Evidently this only works for certain compilers -- in my case, with the pgf90 PGI compiler. It does not work with gfortran.

Upvotes: 1

Views: 98

Answers (1)

This (int(.true.)==-1) is NOT true. Well, at least not in general.

First, you shall not call int() with a logical argument. But your compiler maybe allows it as an extension.

> gfortran realinttrue.f90 
realinttrue.f90:1:13:

 print *,real(.true.), int(.true.)
             1
Error: ‘a’ argument of ‘real’ intrinsic at (1) must have a numeric type
realinttrue.f90:1:26:

 print *,real(.true.), int(.true.)
                          1
Error: ‘a’ argument of ‘int’ intrinsic at (1) must have a numeric type

Perhaps you meant this instead:

print *, transfer(.true.,1)
end

Anyway, the only thing that are guaranteed is that there are two distinct values, TRUE and FALSE. How they look like in memory is up to the compiler. There are two obvious choices. Set all bits to 1, all set the first bits to one. First one is the integer value of -1, the other is +1.

For example, the code above does

> ifort trueint.f90 
> ./a.out 
          -1
> ifort trueint.f90 -standard-semantics
> ./a.out 
 1
> gfortran trueint.f90
> ./a.out 
           1

For real it is even more complicated. I have no idea how you managed to get your result.

Upvotes: 3

Related Questions