Fortran

Guide To Learn

An important aspect of operators, and a common source of bugs for novice programmers, is operator precedence. In other words, which operation gets to go first, and which last? Fortran has a few simple rules for arithmetic operator precedence:

  1. Exponentiation (**) takes precedence over multiplication (*) and division (/). Example: 2**3 * 2 evaluates to 16 (exponentiation first, multiplication second).
  2. Multiplication (*) and division (/) take precedence over addition (+) and subtraction (-). Example: 2 + 3 * 4 evaluates to 14 (multiplication first, addition second).
  3. For operators with equal precedence (* and /, and + and -), the operations are evaluated left to right. The order of operations will matter for floating-point arithmetic.
  4. Parentheses can be used to control the precedence. Example: (2 + 3) * 4**2 evaluates to 80 (addition in parentheses and exponentiation first, multiplication last).

Comparison operators don’t suffer from precedence ambiguity because they operate on numeric or character values, and return a logical value as a result. It’s thus illegal to test, for example, 0 < x < 1, like you can in Python; instead you have to test for 0 < x .and. x < 1. Parentheses are not needed in this case, as the order of operations can be determined by the compiler based on the input data types for different operators.

Operator precedence

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top