next up previous contents index
Next: Guidelines Up: Relational Expressions Previous: Arithmetic Comparisons

Character comparisons

  A character value can only be compared to another character value; if they do not have the same length then the shorter one is padded out with blanks to the length of the other before the comparison takes place. Tests for equality (or inequality) do not depend on the character code, the two strings are just compared character by character until a difference is found. Comparisons using the other operators (.GE., .GT., .LE., and .LT.) do, however, depend on the local character code. The two expressions are compared one character position at a time until a difference is found: the result then depends on the relative positions of the two characters in the local collating sequence, i.e. the order in which the characters appear in the character code table.   The Fortran Standard specifies that the collating sequence used by all systems must have the following basic properties:

It does not, however, specify whether letters precede digits or follow them. As a result, if strings of mixed text are sorted using relational operators the results may be machine dependent. For example, the expression
is always true because at the two strings first differ at the third character position, and the letter 'P' precedes 'R' in all Fortran collating sequences. However:
'A1' .GT. 'AONE'
will have a value true if your system uses EBCDIC but false if it uses ASCII, because the digits follow letters in the former and precede them in the latter.

In order to allow character comparisons to be made in a truly portable way, Fortran has provided four additional intrinsic functions. These perform character comparisons using the ASCII collating sequence no matter what the native character code of the machine. These functions are:

LGE(S1, S2) greater than or equal to
LGT(S1, S2) greater than
LLE(S1, S2) less than or equal to
LLT(S1, S2) less than.

They take two character arguments (of any length) and return a logical value. Thus the expression:
LGT('A1', 'AONE')
will always have the value false.

Character comparisons are case-sensitive on machines which have lower-case letters in their character set. It is advisable to convert both arguments to the same case beforehand.

next up previous contents index
Next: Guidelines Up: Relational Expressions Previous: Arithmetic Comparisons
Helen Rowlands