Operators and precedence

Fortran has more operators than a reader expects, and their precedence is not the precedence of C. The exponentiation operator is right associative, concatenation sits between addition and comparison, and the relational operators do not chain. This lesson prints the results of the ones that surprise people, and states the order the compiler applies them in.

Arithmetic operators

Five operators cover the arithmetic: +, -, *, / and ** for a power. The last one takes an integer exponent and a real or complex base, and it is the only operator Fortran evaluates from right to left, so 2 ** 3 ** 2 is 2 ** 9 and not 8 ** 2 by accident of reading order.

A unary minus binds less tightly than the power: -2 ** 2 is -(2 ** 2), which is -4, and a reader who wants the square of minus two writes (-2) ** 2. That is the opposite of what the mathematical notation "-2²" suggests to some readers and exactly what it suggests to others, which is why the parenthesised form is the only safe one in a program someone else will read.

Division is integer division when both operands are integers, and it truncates toward zero. The lesson on integer arithmetic is about the consequences; here it is enough to see that a / 2 with a = 3 is 1, while a / 2.0 is 1.5.

The file ops.f90:

program ops implicit none integer :: a, b a = 3 b = 4 print *, "2 + 3 * 4 :", 2 + a * b print *, "(2 + 3) * 4 :", (2 + a) * b print *, "2 ** 3 ** 2 :", 2 ** 3 ** 2 print *, "-2 ** 2 :", -2 ** 2 print *, "a / 2 :", a / 2 print *, "a / 2.0 :", a / 2.0 print *, "1 / 3.0 :", 1 / 3.0 print *, "mod(a + 1, 3) :", mod(a + 1, 3) print *, "a > 2 .and. b > 5:", a > 2 .and. b > 5 print *, ".not. a > 2 :", .not. a > 2 print *, '"abc" // "def" :', "abc" // "def" print *, '"abc" < "abd" :', "abc" < "abd" print *, '"a" == "a" :', "a" == "a" end program ops

The last three labels quote a string that itself contains double quotes, so the label is written inside single quotes and the single quote character appears as an entity in the page source. Both quote characters do the same job in Fortran.

gfortran -Wall -Wextra -std=f2018 ops.f90 -o ops
./ops

2 + 3 * 4 : 14
(2 + 3) * 4 : 20
2 ** 3 ** 2 : 512
-2 ** 2 : -4
a / 2 : 1
a / 2.0 : 1.50000000
1 / 3.0 : 0.333333343
mod(a + 1, 3) : 1
a > 2 .and. b > 5: F
.not. a > 2 : F
"abc" // "def" :abcdef
"abc" < "abd" : T
"a" == "a" : T

Precedence

The standard lists the operators in order of decreasing precedence. An operator higher in the list is applied first:

  1. Defined unary operators from a module, which a program can add for its own types.
  2. **, right to left.
  3. * and /, left to right.
  4. Unary + and -, then binary + and -, left to right.
  5. //, the character concatenation.
  6. The six relational operators.
  7. .not.
  8. .and.
  9. .or.
  10. .eqv. and .neqv.

The line that surprises C programmers is the sixth entry. In C, ! binds tighter than ==, so !a == b negates a and then compares. In Fortran .not. a > 2 compares first and negates the comparison, which is why the program above prints F for a value of 3 rather than a type error.

Relational operators

Six comparisons, each of which returns a logical: == and /= for equality, <, <=, > and >= for order. The old spellings .eq., .ne., .lt., .le., .gt. and .ge. are still in the standard and still appear in old code.

Relational operators do not chain. 1 < x < 3 is not an error the compiler catches in every case: 1 < x is a logical, and comparing a logical with an integer is an error, so the build does stop, but with a message about types rather than about the chain. Write 1 < x .and. x < 3.

Comparing reals for equality is legal and usually wrong. Two values computed by different paths differ in the last bit, and the comparison is false for a difference a reader cannot see. Use a tolerance, as the lesson on floating point shows.

Logical operators

.and., .or. and .not. are the three familiar ones, and .eqv. and .neqv. compare two logicals for equality and difference. The program below shows all five, plus the two character intrinsics that a concatenation usually arrives with.

The file logic.f90:

program logic implicit none integer :: a, b a = 3 b = 4 print *, "(a == 3) .eqv. (b == 4):", (a == 3) .eqv. (b == 4) print *, "(a == 3) .neqv. (b == 4):", (a == 3) .neqv. (b == 4) print *, ".not. (a > b) :", .not. (a > b) print *, "a > 2 .or. b < 3 :", a > 2 .or. b < 3 print *, "a > 2 .and. b < 3 :", a > 2 .and. b < 3 print *, "len_trim(""ab "") :", len_trim("ab ") print *, "len(""ab "") :", len("ab ") end program logic

gfortran -Wall -Wextra -std=f2018 logic.f90 -o logic
./logic

(a == 3) .eqv. (b == 4): T
(a == 3) .neqv. (b == 4): F
.not. (a > b) : T
a > 2 .or. b < 3 : T
a > 2 .and. b < 3 : F
len_trim("ab ") : 2
len("ab ") : 5

.or. and .and. do not short-circuit in Fortran. Both operands are evaluated, because either of them may be a function with a side effect, so if (n > 0 .and. x(n) > 0) reads x(n) even when n is zero. The guard must be a nested if or a merge expression, and a compiler may still evaluate both sides of a merge.

Character operators

// joins two character values into one whose length is the sum. Nothing in between is added, not even a space: "abc" // "def" is "abcdef", and a separator has to be written into the literal. The result is a new value of that length, so a loop that builds a string one piece at a time copies the whole string at every step, which is the one performance rule this lesson asks a reader to remember.

The relational operators work on characters and compare them by the collating sequence of the processor, which is ASCII on every platform this course runs on: "abc" < "abd" is true because c comes before d.

The traps of mixed types

Exercises

  1. Print -3 ** 2 and (-3) ** 2. Why do they differ?
  2. Write 1 < a < 5 with a = 3. What does the compiler say?
  3. Replace a / 2.0 with real(a / 2). What does the program print now, and why?
  4. Write a condition that is true only when a is between 1 and 5, using .and..

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which operator is evaluated right to left?

    Answer

    **

    Exponentiation is the one right-associative operator, so 2 ** 3 ** 2 is 512.

  2. What is the value of -2 ** 2?

    Answer

    -4

    The power binds tighter than the unary minus: -(2 ** 2).

  3. Which operator has higher precedence, // or +?

    Answer

    +

    Addition comes before concatenation in the standard precedence table.

  4. What does .not. a > 2 mean in Fortran?

    Answer

    .not. (a > 2)

    Relational operators bind tighter than .not.

  5. What does 1 / 3.0 give?

    Answer

    0.333333343

    The real literal makes the division real, in single precision.

  6. What does mod(a + 1, 3) return for a = 3?

    Answer

    1

    The sum is 4, and 4 modulo 3 is 1.

  7. What does this program print? program p implicit none print *, 2 ** 3 ** 2 end program p

    Answer

    512

    The power is right associative: 3 ** 2 is 9, and 2 ** 9 is 512.

  8. Do .and. and .or. short-circuit in Fortran?

    Answer

    No: both operands are always evaluated

    Both sides are evaluated, so a guard on an array bound cannot be written in one condition.

  9. What is "abc" // "def"?

    Answer

    "abcdef", with no separator

    Concatenation joins the values and adds nothing between them.

  10. What does "abc" < "abd" return?

    Answer

    .true.

    Characters compare by the collating sequence, and c precedes d.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev