Search code examples
fortran

Purpose of KIND= when declaring variables


After spending some time trying to understand how KIND works in Fortran I'm still in doubt. I would like to know if, e.g., INTEGER(KIND = c_intptr_t) is equivalent toINTEGER(c_intptr_t)?

If yes, which way is the preferred way?


Solution

  • As a type declaration the two forms (for kind parameter k) integer (kind = k) and integer (k) are indeed equivalent.

    This is true in type declaration statements

    integer (kind=k) x
    integer (k) y       ! x and y are integers with kind parameter k
    

    and in other places

    x = [integer(kind=k) :: 1, 2, 3]
    y = [integer(k) :: 1, 2, 3]
    

    The same holds for the intrinsic types real(kind=k), complex(kind=k) and logical(kind=k). One has to be careful with character:

    character(kind = k) c  ! Length 1, kind k
    character(k) d         ! Length k, default kind
    character(l, k) e      ! Length l, kind k 
    

    Preferred form is subjective and you should follow your style guide consistently.


    For derived types this is not necessarily the case:

    type t(k)
      integer, kind :: k=58
    end type t
    
    type(t(kind=12)) :: x  ! Not valid: kind parameter is not "kind"
    type(t(k=12)) :: y
    type(t(12)) :: z
    
    end