Fortran: the largest and the smallest integer

echo picture echo · Mar 5, 2012 · Viewed 39.6k times · Source

Fortran is completely new for me, can anybody help me to solve the follwing problem? I want to find out all the integer kind numbers and the largest and the smallest value for each kind number on my pc. I have code listed below:

program intkind
implicit none

integer :: n=1
integer :: integer_range =1


do while(integer_range /= -1)
    print*, "kind_number ", selected_int_kind(n)
    call rang(integer_range)
    n = n *2
    integer_range = selected_int_kind(n)
end do

contains
subroutine rang(largest) 
    integer largest
    print*, huge(largest)

end subroutine

end 

The integer kind numbers what I get are : 1,2,4,8.

  1. Why is each largest integer for each kind number the same: 2147483647? And is there a intrinsic function for the smallest integer?

  2. How can I keep the integer kind number when the subroutine rang is called? I think it is the key to the largest integer.

Answer

Jonathan Dursi picture Jonathan Dursi · Mar 5, 2012

Your subroutine:

subroutine rang(largest) 
    integer :: largest
    print *, huge(largest)
end subroutine

takes as input a default-sized integer, and prints the largest possible value that will fit in that default-sized integer. It will always return huge(default integer) which is, on most systems, huge(4-byte-integer), or 2147483647. huge considers only the variable type; it doesn't interpret the variable in any way. The only way you could do what you're trying to do above is with parameterized derived types, which are new enough that support for it in compilers is still a little spotty.

If you want to take a look at ranges of different KINDs of INTEGERs, you'll have to use different variables:

program integerkinds
    use iso_fortran_env
    implicit none

    integer :: i
    integer(kind=int8)  :: i8
    integer(kind=int16) :: i16
    integer(kind=int32) :: i32
    integer(kind=int64) :: i64

    integer(kind=selected_int_kind(6)) :: j6
    integer(kind=selected_int_kind(15)):: j15

    print *,'Default:'
    print *, huge(i)
    print *,'Int8:'
    print *, huge(i8)
    print *,'Int16:'
    print *, huge(i16)
    print *,'Int32:'
    print *, huge(i32)
    print *,'Int64:'
    print *, huge(i64)

    print *,''

    print *,'Selected Integer Kind 6:'
    print *, huge(j6)

    print *,'Selected Integer Kind 15:'
    print *, huge(j15)

end program integerkinds

Running gives:

$ ./intkinds
 Default:
  2147483647
 Int8:
  127
 Int16:
  32767
 Int32:
  2147483647
 Int64:
  9223372036854775807

 Selected Integer Kind 6:
  2147483647
 Selected Integer Kind 15:
  9223372036854775807