Defining String Variables

Strings are difficult for compilers and interpreters to deal with efficiently, because they vary so much in length. Conserving memory when dealing with strings requires frequently allocating and deallocating small blocks of memory, which is costly in terms of CPU time. The only way to avoid this is by over-allocating strings (e.g. allocate 100 characters for a string even if we only need 12 at the moment). Hence, there is a trade-off to be made between CPU efficiency and memory efficiency.

There are programming techniques to minimize the cost of string manipulation, and thus improve the efficiency of programs that process character data. Some of them will be mentioned in the sections that follow.

A string in Fortran is, for all practical purposes, an array of characters. However, Fortran gives special treatment to strings, so the syntax for working with them is slightly different than it is for arrays of numbers or logical values.

When defining a string, we must indicate the maximum length. The syntax for this changed starting with Fortran 90, but the old syntax used through Fortran 77 is still supported for backward compatibility. All new code should use the Fortran 90 syntax, but older programs using the Fortran 77 syntax will compile with a Fortran 90 compiler.

The Fortran 90 syntax for defining string variables is:

        character(maximum-length) :: name1, name2, ...

As always, we should use named constants to define things like the maximum length of a string.

        module constants
            integer, parameter :: MAX_NAME_LENGTH=40
        end module
        program string_example
            implicit none
            character(MAX_NAME_LEN) :: name
            print *, 'Please enter your name:'
            read *, name
            print *, 'Hello, ', name, '!'
        end program

The Fortran 77 and earlier syntax for defining string variables is:

        character*maximum-length :: name1, name2, ...

This syntax should not be used for new programs. It is presented here so that you will recognize it if you see it in older code.