Skip to content

Assignment, expressions

Assignment

receiving variable = expression. Example:

n = n + 1

The variable and the expression must be both of numerical type, or both logical, or both of character type.

Precedence rules

There are precedence rules between operators (numeric first, then relational, then logical, / and * before + and -, etc.). Use parentheses if necessary. Examples:

  • a / b / c is the same as: a / (b * c)

  • x > y .or. i == k .and. j == l is the same as: x > y .or. (i == k .and. j == l) (.and. has precedence over .or.)

Conversion between numeric types

  • Implicit conversion when assigning a value. Examples:
integer i
real r
i = -1.9 ! receives -1

(truncation, not rounding)

r = 2 ! receives 2.
  • For explicit conversion, use the functions floor and real. Examples: floor(a), real(i).

  • Automatic conversion to real type during evaluation of an expression containing both real and integer operands. Example: 1. / 2

Reminder on integer division

The integral part of the ratio of two positive integer numbers is written in Fortran directly with the / operator, without need for conversion, without calling floor nor real.

For example, suppose we have the two variables:

integer i, j

and we want to compute, in mathematical notation: . In Fortran, if is positive, write simply: (i + j) / 2. Do not write floor((i + j) / 2.).

Other example, if you need the ceiling of , that is, in mathematical notation, , noting that:

you can just write (i + 1) / 2 and not ceiling(i / 2.).

Substring and assignment to character string

  • Substring: v(d:f) v(d:) v(:f) The position of the first character is 1 (and not 0, unlike in Python).

  • Examples:

character(len=8) mot
mot = "aversion"

mot(2:5) equals "vers", mot(6:6) equals "i", mot(2:1) equals ""

  • Assignment: the expression if truncated or padded on the right side with blanks, if necessary.

  • Note: in Fortran, you can modify part of a character variable. Example:

mot = "aversion"
mot(3:) = "ion"

mot equals "avion " (unlike in Python, there is no such thing as an immutable type in Fortran)