Explicit is better than implicit.
The first part of any program unit is the declaration section. Fortran employs a static, manifest, strong typing system:
- Static –Every variable has a data type at compile time, and that type remains the same throughout the life of the program.
- Manifest –All variables must be explicitly declared in the declaration section before their use. An exception and caveat is implicit typing, described in the sidebar.
- Strong –Variables must be type-compatible when they’re passed between a program and functions or subroutines.
Fortran has a historical feature called implicit typing, which allows variable types to be inferred by the compiler based on the first letter of the variable. Yes, you read that right.
Implicit typing comes from the early days of Fortran (ahem, FORTRAN), before type declarations were introduced to the language. Any variable that began with I, J, K, L, M, or N was an integer, and it was a real (floating point) otherwise. FORTRAN 66 introduced data types, and FORTRAN 77 introduced the IMPLICIT statement to override the default implicit typing rules. It wasn’t until Fortran 90 that the language allowed completely disabling the implicit typing behavior by using the statement implicit none before the declaration.
The implicit none statement will instruct the compiler to report an error if you try to use a variable that hasn’t been declared. Always use implicit none!
Intrinsic types are defined by the language standard and are immediately available for use. Fortran has three numeric types:
integer–Whole numbers, such as42or-17real–Floating point numbers, such as3.141or1.82e4complex–A pair of numbers: one for the real part and one for the imaginary part of the complex number; for example,(0.12,-1.33)
Numeric types also come in different kinds. A Fortran kind refers to the memory size that’s reserved for a variable. It determines the permissible range of values and, in the case of real and complex numbers, the precision. In general, higher integer kinds allow a wider range of values. Higher real and complex kinds yield a higher allowed range and a higher precision of values. You’ll learn more about numeric type kinds in chapter 4.
Besides the numerical intrinsic types, Fortran also has the logical type to represent Boolean (true or false) states and character for text data. These five intrinsic types (integer, real, complex, logical, and character) are the basis for all variables in Fortran programs. You also can use them to create compound types of any complexity, called derived types, which are analogous to struct in C and class in Python. We’ll dive deep into derived types in chapter 8.
Tip Always use implicit none. This statement enforces explicit declaration of all variables, which both serves as documentation for the programmer and allows the compiler to find and report type errors for you.