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:
- Exponentiation (
**) takes precedence over multiplication (*) and division (/). Example:2**3*2evaluates to 16 (exponentiation first, multiplication second). - Multiplication (
*) and division (/) take precedence over addition (+) and subtraction (-). Example:2+3*4evaluates to 14 (multiplication first, addition second). - 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. - Parentheses can be used to control the precedence. Example:
(2+3)*4**2evaluates 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