Software Archive
Read-only legacy content
17060 Discussions

logical to integer

wstephens
Beginner
610 Views
What's the easiest and clearest way to convert a logical in the following way:
.false. to 0
.true. to 1
I tried the following code with interesting results:

PROGRAM X

LOGICAL L

L = .TRUE.
WRITE(*,*) L,(-L),(-1*L)
! OUTPUT: T T 1

L = .FALSE.
WRITE(*,*) L,(-L),(-1*L)
! OUTPUT: F F 0

ENDPROGRAM

"L" and "-L" write out the same value!
0 Kudos
4 Replies
Jugoslav_Dujic
Valued Contributor II
610 Views
Most simply:

 
I=0 
IF (L) I=1 


or, more "scientifically":

 
I = IAND( TRANSFER(L, I), 1) 


The behaviour you get is consequence of the fact that in CVF literal .TRUE. TRANSFERs to -1 (#FFFFFFF) while .FALSE. TRANSFERs to 0. However, I
think that in expressions only least significant bit is tested, i.e.

 
L = 24 
IF (L) THEN 
     WRITE(*,*) "TRUE" 
ELSE 
     WRITE(*,*) "FALSE" 
END IF 


displays FALSE, while for L = 25 displays TRUE. CVF non-standardly allows free mixing of LOGICALs and INTEGERs but one should be careful with that
(as the code above shows).

Jugoslav
0 Kudos
Jugoslav_Dujic
Valued Contributor II
610 Views
...couldn't resist to add a funny example:
 
PROGRAM X 
INTEGER:: I 
LOGICAL:: L = .TRUE. 
WRITE(*,*) L + L      !Displays "F" 
END PROGRAM 


Jugoslav
0 Kudos
Jugoslav_Dujic
Valued Contributor II
610 Views
...to put an end to this relentless self-replying, try compiling any of the samples above with "Project/Settings/Fortran Language/Fortran Standards Checking/Fortran95" option.
0 Kudos
Steven_L_Intel1
Employee
610 Views
I'll comment that compiling with the option /fpscomp:logicals changes the interpretation of LOGICAL to match that of PowerStation and C, where 0 is .FALSE. and 1 is .TRUE. When testing an integer as if it were a logical, anything not zero is considered TRUE.

Steve
0 Kudos
Reply