I don't understand that since logical type only has two cases: true
and false
, then why we need logical(1)
,logical(2)
,logical(4)
,logical(8)
in Fortran?
We just need 1 bit
.
Can somebody give an explanation?
First, Fortran doesn't say that we have logical types taking up 1, 2, 4 and 8 bytes each, and they certainly aren't logical(1)
, logical(2)
, logical(4)
, and logical(8)
. An implementation may choose to offer those, calling them those names.
A logical variable can indeed be of only two values. From the (F90, although F2008 says the same in a different place) standard 4.3.2.2:
The logical type has two values which represent true and false.
A processor must provide one or more representation methods for data of type logical. Each such method is characterized by a value for a type parameter called the kind type parameter.
[Emphasis here and later verbatim.]
For a logical type of default kind the rules of storage association (14.6.3.1) say that:
(1) A nonpointer scalar object of type default integer, default real, or default logical occupies a single numeric storage unit.
(5) A nonpointer scalar object of type [..] nondefault logical [..] occupies a single unspecified storage unit that is different for each case.
So, the compiler must offer a logical type which is of the same size as an integer and real type, but, equally, it can offer representations taking up 1 bit, 1 byte, or whatever. The kind number, and size, for any given representation (hence my first paragraph: the question isn't universally valid) is implementation-specific. That said, there is no SELECTED_LOGICAL_KIND
(or such) intrinsic until Fortran 2023.
As to why multiple representations can be useful, that comes down to offering a choice, perhaps for special cases such as for arrays and ideal memory management (some people like to play non-portable tricks). However, memory access/alignment requirements suggest that a scalar logical would be at least one byte (or padding make it the same). For C interoperability (F2003+) there is a kind C_BOOL
corresponding to the companion C processor's _Bool
, which needn't be the same size.