Fortran comes with a number of built-in operators. Each falls into one of four categories, depending on what type of result they produce:
- Arithmetic –These are the most common kind of operators in almost any computer program. They allow you to do arithmetic calculations, such as add, subtract, multiply, and divide numbers. Arithmetic operators work on numeric values and produce a numeric value as a result.
- Comparison –These operators let you compare the values of variables to yield logical values, such as
True(.true.) orFalse(.false.). You can compare numeric or character values (character string comparisons are evaluated based on the integer encoding of Unicode symbols), and the result is always a logical.true.or.false.. - Logical –These allow you to form logical (Boolean) expressions from two fundamental logical states,
TrueandFalse. For example, if you’d require both expressionsaandbto beTrue, you’d test for the value ofa.and.b. If you’d need at least one of them to beTrue, you’d test it witha.or.b. Logical operators always operate onlogicaloperands and producelogicalresults. In contrast to all other built-in operators, logical operators are always enclosed in period symbols:.and.,.or.,.not., etc. - Character –Fortran offers only one operator that works on character strings, the concatenation operator
//.
There’s also the special assignment operator =. What’s special about it is that rather than returning a value of some data type, it acts to store the result on the right side into the variable on the left side. The assignment operator is by default available for use with all built-in types, as well as user-defined derived types, if the type of the expression on the right side matches the type of the variable on the left side. The assignment can be redefined, just as any other operator can, and to great effect. We’ll dig deeper into this in the next chapter, where we’ll redefine the assignment for Field types in the tsunami simulator to automatically synchronize parallel processors on assignment.
Due to the nature of these operators, there are typical scenarios in which you’ll use them. Arithmetic operators are most commonly used in numerical calculations with assignments to new variables. Comparison and logical operators are often used together to test for conditions and criteria in if/else statements. Finally, character string concatenation is almost exclusively used for text manipulation and I/O.
Table 9.3 summarizes the built-in operators.
Table 9.3 Summary of Fortran’s built-in operators, and their meanings
In total, Fortran provides five arithmetic operators, six comparison operators, five logical operators, and one character string operator.
Note that Fortran doesn’t allow comparing logical expressions with the == or /= operators. Use .eqv. (equivalent) or .neqv. (not equivalent) instead.