Some explanation needed about kind example

This is an example from Ian Chivers book:

program ch0509

  implicit none

! example of the use of the kind function
! and the numeric inquiry functions
! for integer kind types

! 8 bit            -128  to
! 127      10**2

! 16 bit          -32768 to
! 32767     10**4

! 32 bit     -2147483648 to
! 2147483647     10**9

! 64 bit
! -9223372036854775808 to
! 9223372036854775807    10**18

  integer :: i
  integer, parameter :: i8 = selected_int_kind(2)
  integer, parameter :: i16 = selected_int_kind(4)
  integer, parameter :: i32 = selected_int_kind(9)
  integer, parameter :: i64 = selected_int_kind(18)
  integer (i8) :: i1
  integer (i16) :: i2
  integer (i32) :: i3
  integer (i64) :: i4

  print *, ' '
  print *, ' integer kind support'
  print *, ' kind           huge'
  print *, ' '
  print *, ' ', kind(i), ' ', huge(i)
  print *, ' '
  print *, ' ', kind(i1), ' ', huge(i1)
  print *, ' ', kind(i2), ' ', huge(i2)
  print *, ' ', kind(i3), ' ', huge(i3)
  print *, ' ', kind(i4), ' ', huge(i4)
  print *, ' '
end program

An integer i is declared but not initialized. On my system it gets initialized to 0 although afaik this is not mandatory.
Now the output with ifort compiler gives:


  integer kind support
  kind           huge

             4    2147483647

             1    127
             2    32767
             4    2147483647
             8     9223372036854775807

It looks like kind(i) in this case kind(0) turns out to be 4.
I suppose there is a perfectly logical explanation but as I’m afraid I don’t see it.

Roger

The kind of a variable is known from its declaration, even if it has not been set. A declaration

integer :: i

means that i is of the type default integer, and most compilers use 4 for the kind number of default integers, although this should not be relied upon.

3 Likes

Thank you.

Verzonden vanaf Outlook voor Android

The value of i, which is declared as a default integer, is not needed in the program, only its type and kind are required. Values are also not assigned or initialized to i1, i2, i3, and i4, and that is allowed for the same reason. On most compilers, there are options that allow the default kind to be changed, in which case the first line of the output would be different and would presumably match one of the other output lines.

OK, thank you.

This kind concept in fortran is a bit confusing for a beginner.

Note that your variables i1, …, i4 are not explicitly initialized either, and are probably equal to zero as well. Yet kind(i1)... return what you are expecting. In kind(<variable_or_constant>), the value of the variable of constant doesn’t matter.

Thanks! Got it.