Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fortran: integer*4 vs integer(4) vs integer(kind=4)

I'm trying to learn Fortran and I'm seeing a lot of different definitions being passed around and I'm wondering if they're trying to accomplish the same thing. What is the difference between the following?

  • integer*4
  • integer(4)
  • integer(kind=4)
like image 609
Sam Avatar asked Jul 03 '10 03:07

Sam


People also ask

What does integer * 4 mean in Fortran?

The integer data type, INTEGER*4 , holds a signed integer. An INTEGER*4 occupies 4 bytes. INTEGER*4 is aligned on 4-byte boundaries.

What does kind mean in Fortran?

The KIND of a variable is an integer label which tells the compiler which of its supported kinds it should use. Beware that although it is common for the KIND parameter to be the same as the number of bytes stored in a variable of that KIND, it is not required by the Fortran standard.

How do I convert real to int in Fortran?

A real number can be converted to an integer one using the int intrinsic function. Note that int function simply truncates its real argument.


1 Answers

In Fortran >=90, the best approach is use intrinsic functions to specify the precision you need -- this guarantees both portability and that you get the precision that you need. For example, to obtain integers i and my_int that will support at least 8 decimal digits, you could use:

integer, parameter :: RegInt_K = selected_int_kind (8) integer (kind=RegInt_K) :: i, my_int 

Having defined RegInt_K (or whatever name you select) as a parameter, you can use it throughout your code as a symbol. This also makes it easy to change the precision.

Requesting 8 or 9 decimal digits will typically obtain a 4-byte integer.

integer*4 is an common extension going back to old FORTRAN to specify a 4-byte integer. Although, this syntax isn't and was never standard Fortran.

integer (4) or integer (RegInt_K) are short for integer (kind=4) or integer (kind=RegInt_K). integer (4) is not the same as integer*4 and is non-portable -- the language standard does not specify the numeric values of kinds. Most compilers use the kind=4 for 4-byte integers -- for these compilers integer*4 and integer(4) will provide the same integer type -- but there are exceptions, so integer(4) is non-portable and best avoided.

The approach for reals is similar.

UPDATE: if you don't want to specify numeric types by the required precision, but instead by the storage that they will use, Fortran 2008 provides a method. reals and integers can be specified by the number of bits of storage after useing the ISO_FORTRAN_ENV module, for example, for a 4-byte (32-bit) integer:

use ISO_FORTRAN_ENV integer (int32) :: MyInt 

The gfortran manual has documentation under "intrinsic modules".

like image 121
M. S. B. Avatar answered Oct 17 '22 06:10

M. S. B.