Operator precedence: Difference between revisions
Added C# |
m Fixed C# link |
||
Line 734:
=={{header|C sharp|C#}}==
[
=={{header|Caché ObjectScript}}==
|
Revision as of 11:26, 25 October 2022
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Operators in C and C++. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) |
- Task
Provide a list of precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it.
Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction.
State whether arguments are passed by value or by reference.
11l
See 11l documentation.
8th
In 8th it's very simple: the currently invoked word has precedence, and items are operated upon in the order they are popped off the stack.
6502 Assembly
There are two types of indirect addressing: Indirect X and Indirect Y. These differ in that the indirect X mode applies the offset before looking up the address.
LDX #$02
LDY #$03
LDA ($20,x) ;uses the values stored at $20+x and $21+x as a memory address, and reads the byte at that address.
LDA ($20),y ;uses the values store at $20 and $21 as a memory address, and reads the byte at that address + Y.
The use of parentheses for these modes is required, and nicely illustrates the order of operations. To put it in terms of a hierarchy:
Highest: Indirection: () Middle: Offsetting: ,x ,y Lowest: Reading at the specified address.
Ada
Ada Reference Manual, ISO/IEC 8652:2012(E), section 4.5. "Operators and Expression Evaluation" contains the listing.
Operator | Description | Operator | Description | Operator | Description | Operator | Description |
---|---|---|---|---|---|---|---|
** |
Power | abs |
Absolute | not |
Logical Negate | ||
* |
Multiply | / |
Divide | mod |
Modulus | rem |
Remainder |
+ |
Unary Add (Identity) | - |
(Unary) Negate | ||||
+ |
Binary Add | - |
Binary Subtract | & |
Concatenation | ||
= |
Equals | /= |
Not Equal | < <= |
Less, Less or Equal | > >= |
More, More or Equal |
and |
And | or |
Or | xor |
XOR |
ALGOL 60
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | power | 'POWER' |
left |
2 | unary operator (opposite) | + - |
left |
3 | multiplication & division | * / '/' |
left |
4 | addition & subtraction | + - |
left |
5 | comparison | 'EQUAL' 'NOT EQUAL' |
left |
6 | logical NOT | 'NOT' |
left |
7 | logical AND | 'AND' |
left |
8 | logical OR | 'OR' |
left |
9 | equivalence | 'EQUIV' |
left |
10 | implication | 'IMPL' |
left |
lowest |
Note: '/' is the Euclidean division
ALGOL 68
The coder may define new operators and both those and the pre-defined ones may be overloaded and their priorities may be changed.
Array, Procedure, Dereference, Selection and Generator operations
priority | Operation | +Algol68Rev0 | +Algol68G |
---|---|---|---|
Effectively 12 (Primary) |
dereferencing, deproceduring(~,~), subscripting[~], rowing[~,] & slicing[~:~] | currying(~,), diag, trnsp, row, col | |
Effectively 11 (Secondary) |
of (selection), loc & heap (generators) | → | new (generator) |
These are technically not operators, rather they are considered "units associated with names"
Monadic operators
priority (Tertiary) |
Algol68 "Worthy characters" | +Algol68Rev0&1 | +Algol68C,G | +Algol68Rev0 |
---|---|---|---|---|
10 | not, up, down, lwb, upb,
-, abs, arg, bin, entier, leng, level, odd, repr, round, shorten |
¬, ↑, ↓, ⌊, ⌈ | ~, norm, trace, t, det, inv | lws, ups, ⎩, ⎧, btb, ctb |
Standard dyadic operators with associated priorities
priority (Tertiary) |
Algol68 "Worthy characters" | +Algol68Rev0&1 | +Algol68C,G | +Algol68Rev0 |
---|---|---|---|---|
9 | +*, i | +×, ⊥ | ! | |
8 | shl, shr, **, up, down, lwb, upb | ↑, ↓, ⌊, ⌈ | lws, ups, ⎩, ⎧ | |
7 | *, /, %, over, %*, mod, elem | ×, ÷, ÷×, ÷*, %×, □ | ÷: | |
6 | -, + | |||
5 | <, lt, <=, le, >=, ge, >, gt | ≤, ≥ | ||
4 | =, eq, /=, ne | ≠ | ~= | |
3 | &, and | ∧ | /\ | |
2 | or | ∨ | \/ | |
1 | minusab, plusab, timesab, divab, overab, modab, plusto,
-:=, +:=, *:=, /:=, %:=, %*:=, +=: |
×:=, ÷:=, ÷×:=, ÷*:=, %×:= | minus, plus, div, overb, modb, ÷::=, prus |
Note: Tertiaries include names nil and ○.
Assignation and identity relations etc
Again, these are technically not operators, rather they are considered "units associated with names"
priority (Quaternaries) |
Algol68 "Worthy characters" | +Algol68Rev0&1 | +Algol68C | +Algol68Rev0 |
---|---|---|---|---|
Effectively 0 | :=, =:, = , :=:, :/=:, is, isnt, at , @ | :≠:, : | :~=: | ct, ::, ctab, ::=, .., is not |
Note: Quaternaries include names skip and ~.
Algol 68 also includes (something like) C's ternary conditions, e.g.:
- case ~ in ~ ouse ~ in ~ out ~ esac or simply "( ~ | ~ |: ~ | ~ | ~ )",
- if ~ then ~ elif ~ then ~ else ~ fi or simply "( ~ | ~ |: ~ | ~ | ~ )",
And (unlike C's comma operator) the ";" can be used to indicate statements are done sequentially, where as the "," indicates that the statements can be done "collaterally", e.g. in parallel. Or a parallel clause can be used to force statements to be executed in parallel, e.g. par( ~, ~, ... )
Key: The super scripts indicate the following:
- ALGOL 68Rev0 indicates Algol 68 Final Report (Essentially Revision 0)
- ALGOL 68Rev0&1 indicates Algol 68 Revised Report (Essentially Revision 1)
- ALGOL 68C indicates Cambridge University Algol 68[1].
- ALGOL 68G indicates Algol 68 Genie[2]
ALGOL W
Priority | Operator | Description | Associativity | Arity |
---|---|---|---|---|
highest | long short abs | Widen, narrow, absolute value | left | unary |
shl shr ** | left shift, right shift, raise to power | left | binary | |
* / div rem | multiply, divide, integer division, remainder | left | binary | |
+ - | addition, subtraction | left | unary and binary | |
< <= = ¬= >= > is | comparison, "is" checks a reference has a particular type | left | binary | |
not | logical or bits negation | left | unary | |
and | logical or bits "and" | left | binary | |
lowest | or | logical or bits "or" | left | binary |
AppleScript
From the AppleScript Language Guide, plus additional notes:
Order | Operators | Associativity | Type | Additional notes |
---|---|---|---|---|
1 | ( ) | Innermost to Outermost | Grouping | |
2 | + - | Unary | Plus or minus sign for numbers | Plus sign omitted in compiled code. |
3 | ^ | Right to left | Exponiation | Sequences automatically parenthesised in compiled code. |
4 | * / div mod | Left to right | Multiplication and division | Also work with numeric text, giving integer or real results. |
5 | + - | Left to right | Addition and subtraction | Ditto. |
6 | & | Left to right | Concatenation | If the right operand can't be coerced to the left's class, the result is a list containing both operands. |
7 | as | Left to right | Coercion | |
8 | < ≤ > ≥ | None | Comparison | Also terms like is less than, is not greater than or equal to, etc. Mixtures of numbers and numeric text are compared as per the class of the left operand. |
9 | = ≠ | None | Equality and inequality | Also terms like is and is equal to. Class and value are both considered. |
10 | not | Unary | Logical negation | Sequences automatically parenthesised in compiled code. |
11 | and | Left to right | Logical and | |
12 | or | Left to right | Logical or |
Arturo
There is no need for operator precedence in Arturo, since all expressions are parsed/evaluated in the exact same way.
The main expression evaluation order of Arturo is right-to-left. But with a tiny asterisk: Your code will be evaluated from left to right, it is the expressions passed to your function calls that will be evaluated from right-to-left.
This works for mathematical expressions too, since they are treated as normal function calls.
See Arturo documentation.
print 2 + 3 * 5 ; same as 2 + (3 * 5)
print 3 * 5 + 2 ; same as 3 * (5 + 2)
- Output:
17 21
AWK
See also: gawk-Reference
# Operators are shown in decreasing order of precedence.
# A blank line separates groups of operators with equal precedence.
# All operators are left associative except:
# . assignment operators
# . conditional operator
# . exponentiation
# which are right associative.
#
# ( ) grouping
#
# $ field reference
#
# ++ increment (both prefix and postfix)
# -- decrement (both prefix and postfix)
#
# ^ exponentiation
# ** exponentiation (not all awk's)
#
# + unary plus
# - unary minus
# ! logical NOT
#
# * multiply
# / divide
# % modulus
#
# + add
# - subtract
#
# string concatenation has no explicit operator
#
# < relational: less than
# <= relational: less than or equal to
# > relational: greater than
# >= relational: greater than or equal to
# != relational: not equal to
# == relational: equal to
# > redirection: output to file
# >> redirection: append output to file
# | redirection: pipe
# |& redirection: coprocess (not all awk's)
#
# ~ regular expression: match
# !~ regular expression: negated match
#
# in array membership
#
# && logical AND
#
# || logical OR
#
# ?: conditional expression
#
# = assignment
# += addition assignment
# -= subtraction assignment
# *= multiplication assignment
# /= division assignment
# %= modulo assignment
# ^= exponentiation assignment
# **= exponentiation assignment (not all awk's)
BASIC256
Operators are evaluated according to a strict set of rules. These rules are called the “Order of Operations”.
Priority | Operator(s) | Category/Description |
---|---|---|
highest | () | Grouping |
10 | ^ | Exponent |
9 | - ~ | Unary Minus and Bitwise Negation (NOT) |
8 | * / \ | Multiplication, Division, and Integer Division |
7 | % | Integer Remainder (Mod) |
6 | + - ; | Addition/Concatenation, and Subtraction |
5 | & | | Bitwise And and Bitwise Or |
4 | < <= > >= = <> | Comparison (Numeric and String) |
3 | NOT | Logical Not |
2 | AND | Logical And |
1 | OR | Logical Or |
lowest | XOR | Logical Exclusive Or |
bc
From the POSIX Standard, ordered by decreasing precedence:
Precedence | Operator(s) | Description | Associativity |
---|---|---|---|
Highest | ++, -- | Prefix/Postfix Increment/Decrement | n/a |
unary - | Negation | n/a | |
^ | Exponentiation | Right to left | |
*, /, % | Multiplication, Division, Remainder | Left to right | |
+, binary - | Addition, Subtraction | Left to right | |
=, +=, -=, *=, /=, %=, ^= | Assignment | Right to left | |
==, <=, >=, !=, <, > | Comparison | None | |
! | Logical Not | n/a | |
&& | Logical And | Left to right | |
Lowest | || | Logical Or | Left to right |
BCPL
In the table below, L indicates left associativity and R indicates right associativity.
Priority | Operator | Notes |
---|---|---|
9 | Names, Literals, ?
| |
TRUE , FALSE , BITSPERBCPLWORD
| ||
(E) | ||
9L | SLCT , : |
Field selectors |
Function and method calls | ||
Subscripted expressions using [ and ]
| ||
8L | ! , % , OF |
Dyadic |
7 | ! , @ |
Prefixed |
6L | * , / , MOD
| |
5 | + , - , ABS |
Dyadic and monadic |
4 | = , ~= , <= , >= , < , > |
Extended relations |
4L | << , >> |
Bit shift operators |
3 | ~
| |
3L | &
| |
2L | |
| |
1L | EQV , XOR
| |
1R | -> , |
Conditional expression |
0 | VALOF , TABLE
|
BQN
The operators of most popular programming languages correspond to functions in BQN (all functions, builtin and defined, are infix).
However, modifiers (higher order functions) have higher precedence over functions.
Here, 2 + 1
is evaluated first:
3 * 2 + 1
Here, -˜
is evaluated first. ˜
flips the arguments given to a function.
3 * 2 -˜ 1
A precedence table for all BQN syntax is shown below.
Precedence | Role | Associativity | Examples and comments |
---|---|---|---|
Highest | Brackets | ()⟨⟩{}[]
| |
. |
Left | Namespace field access | |
‿ |
Stranding (forms lists); really an n-ary instead of binary operator | ||
Modifier | Left | e.g. ∘⎉¨´ , also modified assignment ↩ in Fn↩
| |
Function | Right | e.g. +↕⊔⍉ (including in trains), also assignment ←↩⇐
| |
Lowest | Separator | ⋄, and newline, and block punctuation ;:?
|
Bracmat
Bracmat has 15 binary operators and 12 unary operators, not counting the minus
The binary operators have a simple precedence order and all binary operators are right-associative.
Precedence | Operator | Description | Example | Note |
---|---|---|---|---|
Highest | _ |
In pattern: matches any binary operator. Outside pattern: evaluates to last matched operator | a*b:?x_?y & p_q becomes p*q
| |
$ |
Function application. Evaluates rhs and then applies function on lhs | put$!x
| ||
' |
Function application. Applies function on lhs to unevaluated rhs | apply'(?a 13 ?z)
| ||
\D |
Symbolic differentiation | x\D(x^2) differentiates x^2 to x
| ||
\L |
Logarithm | e\Ly is the natural logarithm of y
| ||
^ |
Exponentiation | x^2 is the square of x
| ||
* |
Multiplication | a*b is the product of a and b |
neutral element: 1
| |
+ |
Addition | a+b is the sum of a and b |
neutral element: 0
| |
white space | constructs a white space separated list | a b |
neutral element: empty string ""
| |
: |
Match subject on the left with pattern on the right | a b c d:? c ?
| ||
& |
"and then" | 1:2 & out$"The end of time is nearing"
| ||
| | "or else" | 1:2 | out$"Don't think so"
| ||
, |
constructs a comma separated list | 1,2,3
| ||
. |
constructs a dot separated list or tree in general | (aa.bb).cc.dd
| ||
Lowest | = |
define | swap=a b.!arg:(?a.?b)&(!b.!a)
|
Precedence among unary operators is a mixed bag. Unary operators can modify something that is to the right of the unary operator, which can be another unary operator, a string or a binary operator.
Of the unary operators ?
and !
(or !!
), the latter have the higher priority. So 17:?!x
assigns the value 17
to the variable that happens to be the value of x
. (Like *x = 17
in C). (The unary operators !
and !!
cannot be combined and are reduced to !!
)
The negation operator ~
negates the first of the unary operators / # < > % @
that is present. If none of these unary operators is present, the negation operator negates the node (string or expression with binary operator) itself, with the meaning "not equal to". Bang operators !
or !!
turn their operand into a variable that is supposed to have a value. The negation operator operates on the value (direct resp. indirect) of a variable, not on the variable name itself.
The combination ~<>
has to be read in one piece, meaning "not unequal", which is not quite unequal to ~
. It is used for case insensitive matching.
Some combinations of unary operators have currently no meaning and are silently reinterpreted: ~?x
is the same as ?x
and ~?!x
is the same as ?!x
. But ~#?x
is not the same as #?x
.
The [
and `
(grave accent) are outside any considerations of precedence.
If you are wondering what the discussed unary operators are for, see this table:
Operator | Description | Example |
---|---|---|
! or !! |
retrieves value | (x=17)&!x becomes 17
|
? |
(In a pattern) Assigns value. Or is a wildcard. | 1 2 3:?x 3 ? & !x becomes 1 2
|
` |
Cuts corners, like FENCE in SNOBOL4 or ! in Prolog |
1 2 3:? `?x 3 assigns 2 to x , because assigning 1 2 is never tried.
|
@ |
Accept atomic subjects only | 2*a+3*b+c+6*d:?+@+? succeeds, because c is atomic.
|
% |
Accept anything but neutral element | 8 2 3:%?x ? assigns 8 to x
|
> ( < ) |
Greater (less) than | 1 2 3 4:? >%@2 ?x assigns 4 to x
|
# |
Accept only a number | a:#*?x assigns a to x and matches 1 with #
|
/ |
Accept only a non-integer number | 1 2 5/2 3:? /?x ? assigns 5/2 to x
|
~ |
Negate | a:~b (succeeds) 5:~<5 (succeeds)
|
[ |
Catches position in subject rather than part of the subject itself | a b c d:? [?p&!p gives 4 , the length of the subject in number of elements. a b c d:? [2 ?x assigns c d to x .
|
C
Same as C++.
C++
The following is a table that lists the precedence and associativity of all the operators in the C and C++ languages. An operator's precedence is unaffected by overloading.
Precedence | Operator | Description | Associativity |
---|---|---|---|
1
highest |
::
|
Scope resolution (C++ only) | Left-to-right |
2 | ++
|
Suffix increment | |
--
|
Suffix decrement | ||
()
|
Function call | ||
[]
|
Array subscripting | ||
.
|
Element selection by reference | ||
->
|
Element selection through pointer | ||
typeid()
|
Run-time type information (C++ only) (see typeid) | ||
const_cast
|
Type cast (C++ only) (see const cast) | ||
dynamic_cast
|
Type cast (C++ only) (see dynamic cast) | ||
reinterpret_cast
|
Type cast (C++ only) (see reinterpret cast) | ||
static_cast
|
Type cast (C++ only) (see static cast) | ||
3 | ++
|
Prefix increment | Right-to-left |
--
|
Prefix decrement | ||
+
|
Unary plus | ||
-
|
Unary minus | ||
!
|
Logical NOT | ||
~
|
Bitwise NOT | ||
(type)
|
Type cast | ||
*
|
Indirection (dereference) | ||
&
|
Address-of | ||
sizeof
|
Size-of | ||
new , new[]
|
Dynamic memory allocation (C++ only) | ||
delete , delete[]
|
Dynamic memory deallocation (C++ only) | ||
4 | .*
|
Pointer to member (C++ only) | Left-to-right |
->*
|
Pointer to member (C++ only) | ||
5 | *
|
Multiplication | |
/
|
Division | ||
%
|
Modulo (remainder) | ||
6 | +
|
Addition | |
-
|
Subtraction | ||
7 | <<
|
Bitwise left shift | |
>>
|
Bitwise right shift | ||
8 | <
|
Less than | |
<=
|
Less than or equal to | ||
>
|
Greater than | ||
>=
|
Greater than or equal to | ||
9 | ==
|
Equal to | |
!=
|
Not equal to | ||
10 | &
|
Bitwise AND | |
11 | ^
|
Bitwise XOR (exclusive or) | |
12 | |
|
Bitwise OR (inclusive or) | |
13 | &&
|
Logical AND | |
14 | ||
|
Logical OR | |
15 | ?:
|
Ternary conditional (see ?:) | Right-to-left |
16 | =
|
Direct assignment | |
+=
|
Assignment by sum | ||
-=
|
Assignment by difference | ||
*=
|
Assignment by product | ||
/=
|
Assignment by quotient | ||
%=
|
Assignment by remainder | ||
<<=
|
Assignment by bitwise left shift | ||
>>=
|
Assignment by bitwise right shift | ||
&=
|
Assignment by bitwise AND | ||
^=
|
Assignment by bitwise XOR | ||
|=
|
Assignment by bitwise OR | ||
17 | throw
|
Throw operator (exceptions throwing, C++ only) | |
18 | ,
|
Comma | Left-to-right |
For quick reference, see also this equivalent, color-coded table.
C#
Caché ObjectScript
There is no operator precedence in COS or in MUMPS. It is evaluated left-to-right. Operations can be forced to evaluate in a specific order using parentheses. Example:
- Output:
SAMPLES>write 18 / 2 * 3 + 734 SAMPLES>write 18 / (2 * 3) + 7 10
Clojure
As is the case with LISPs in general, there is no need to worry about operator precedence. This is one of the benefits of S-Expressions and prefix notation. All functions evaluate left to right and inside out. The operators in Clojure are just functions, and everything is fully parenthesized.
That being said, there is a macro expansion phase that precedes compilation, and with macros you have great power to change the rules. A couple of the most common macros with respect to ordering are the thread-first macro and the thread-last macro. These allow you to order expressions as a chain, which in many cases is preferable for readability.
COBOL
The following data was derived from the 2009 draft COBOL 20XX Standard.
Arithmetic Expressions
Precedence | Operator(s) | Description |
---|---|---|
Highest | + - |
Unary plus and minus |
** |
Exponentiation | |
* / |
Multiplication and Division | |
Lowest | + - |
Addition and Subtraction |
Boolean Expressions
Precedence | Operator | Description |
---|---|---|
Highest | B-NOT |
Negation |
B-AND |
Conjunction | |
B-XOR |
Exclusive disjunction | |
Lowest | B-OR |
Inclusive disjunction |
Concatenation Expressions
The &
operator is the only operator used in concatenation expressions.
Logical Expressions
Precedence | Operator | Description |
---|---|---|
Highest | NOT |
Logical negation |
AND |
Logical conjunction | |
Lowest | OR |
Logical inclusive OR |
Common Lisp
There is no need to worry about operator precedence in Common Lisp and Lisp's in general. Operators (like + - * / ) are normal functions and all of the code is organized as S-expressions with a prefixed polish notation. In result all of the code is parenthesized and the code is evaluated from the innermost S-expression to the outermost S-expression.
D
Priority | Description | Operators | Comments | |
---|---|---|---|---|
15 | Template instantiation | ! | Top-level ',' in rhs expression treated specially. Cannot be chained | |
14.5 | Lambda abstraction | => | Not a real operator, occurs twice, this is binding power to the left. | |
14 | Postfix operators | . ++ -- ( [ | ( and [ treat top-level ',' in rhs expression specially and require balanced ) or ] in order to be completed | |
13 | Power operator | ^^ | Right-associative | |
12 | Unary operators | & ++ -- * + - ! ~ | ||
11 | - | * / % | ||
10 | - | + - ~ | Binary '~' is the concatenation operator | |
9 | Bit shift operators | << >> >>> | ||
6a | Comparison operators | == != > < >= <= !> !< !>= !<= <> !<> <>= !<>= in !in is !is | Unordered with respect to bitwise operators, cannot be chained. | |
8b | Bitwise AND | & | Unordered with respect to comparison operators | |
7b | Bitwise XOR | ^ | Unordered with respect to comparison operators | |
6b | Bitwise OR | | | Unordered with respect to comparison operators | |
5 | Logical AND | && | Short-circuit | |
4 | Logical OR | || | Short-circuit | |
3 | Conditional operator | ?: | Right-associative | |
2 | Assignment operators | = -= += <<= >>= >>>= = *= %= ^= ^^= ~= | Right-associative | |
1.5 | Lambda abstraction | => | Not a real operator, occurs twice, this is binding power to the right | |
1 | Comma operator | , | Not to be confused with other uses of ',', though their precedence is the same | |
0 | Range separator | .. | Not a real operator, hardwired into syntax at specific points |
Delphi
See table at Free Pascal.
Eiffel
Official documentation: [[3]], section 8.28.5
Priority | Operator | Description | Associativity |
---|---|---|---|
13
Highest |
.
|
Dot notation, in qualified and non-object calls | |
12 | old
|
Used in postconditions to denote the value an expression had before routine entry | |
not
|
Unary negation | ||
+
|
Unary plus | ||
-
|
Unary minus | ||
All free unary operators | Custom unary aliases (See note below table) | ||
11 | All free binary operators | Custom binary aliases (See note below table) | |
10 | ^
|
Power operator | Right-to-left |
9 | *
|
Multiplication | Left-to-right |
/
|
Division | ||
//
|
Integer division | ||
\\
|
Integer remainder (modulo) | ||
8 | +
|
Addition | Left-to-right |
-
|
Subtraction | ||
7 | ..
|
To define an interval | |
6 | =
|
Equality (reference) | |
/=
|
Inequality (reference) | ||
~
|
Equality (object, uses x.is_equal(y) assuming x /= Void) | ||
/~
|
Inequality (object, uses x.is_equal(y) assuming x /= Void) | ||
<
|
Less than | ||
>
|
Greater than | ||
<=
|
Less than or equal | ||
>=
|
Greater than or equal | ||
5 | and
|
Conjunctive Boolean operator (strict) | Left-to-right |
and then
|
Conjunctive Boolean operator (semistrict — short-circuit) | ||
4 | or
|
Disjunctive Boolean operator (strict) | Left-to-right |
or else
|
Disjunctive Boolean operator (semistrict — short-circuit) | ||
xor
|
Exclusive disjunctive Boolean operator | ||
3 | implies
|
Implicative Boolean operator (( a implies b ) = ( not a or else b ))
|
Left-to-right |
2 | [ ]
|
Manifest tuple delimiter | |
1
Lowest |
;
|
Optional semicolon between an assertion clause and the next |
Any sequence of free operators (that does not already have a defined meaning, such as =
or ?
) can be used as an alias for unary or binary operations.
The set of free operators is:
: \ ? = ~ / ! # $ % & * + - < > @ ^ ` | , ' ;
Special binary aliases such as ()
and []
can also be used.
Refer to section 8.32.21 of the aforementioned link for more details.
Erlang
Official documentation table: [[4]]
Operators | Associativity |
---|---|
: |
|
# |
|
(unary) + , (unary) - , bnot , not |
|
/ , * , div , rem , band , and |
Left |
+ , - , bor , bxor , bsl , bsr , or , xor |
Left |
++ , -- |
Right |
== , /= , =< , < , >= , > , =:= , =/= |
|
andalso |
|
orelse |
|
= , ! |
Right |
catch
|
F#
Factor
Because Factor uses postfix notation and relies entirely on fixed-argument function composition, all operators have the same precedence. Think of using a calculator that uses reverse-polish notation. Instead of writing (3+5)*2, you'd write 3 5 + 2 *. There is no need for parentheses to clarify the order of operations.
Forth
Forth as the language of a stack machine does not require operator precedence. Since all arguments for operations are taken from the stack the order is simply left to right, in the order of the source code. Even the brackets used for the S-expression are not needed with reverse Polish notation.
Fortran
Operators | Details |
---|---|
Function calls | |
** |
Numeric |
* , / |
Numeric |
+ , - |
Unary numeric operators |
+ , - |
Binary numeric operators |
// |
String |
FROM , TO |
|
.EQ. , .GE. , .GT. , .LE. , .LT. , .NE. , == , >= , > , <= , < , /= |
Relational |
.NOT. , # |
Logical |
.AND. , & |
Logical |
.OR. , | |
Logical |
.EQV. , .NEQV. |
Logical |
, |
|
(, ) |
|
Start and End of an expression |
FreeBASIC
If operators have equal precedence, they then are evaluated in the order in of their associativity. The associativity may be Left-to-Right or Right-to-Left order.
As a rule, binary operators (such as +, ^) and unary postfix operators (such as (), ->) are evaluated Left-to-Right, and unary prefix operators (such as Not, @) are evaluated Right-to-Left.
Operators that have an associativity of "N/A" indicate that there is no expression in which the operator can be used where its order of operation would need to be checked, either by precedence or by associativity. Function-like operators such as Cast are always the first to be evaluated due to the parentheses required in their syntax. And assignment operators are always the last to be evaluated.
Parentheses can be used to override operator precedence. Operations within parentheses are performed before other operations
Priority | Operator | Description | Associativity |
---|---|---|---|
highest | CAST | Type Conversion | N/A |
highest | PROCPTR | Procedure pointer | N/A |
highest | STRPTR | String pointer | N/A |
highest | VARPTR | Variable pointer | N/A |
18 | [] | String index | Left-to-Right |
18 | [] | Pointer index | Left-to-Right |
18 | () | Array index | Left-to-Right |
18 | () | Pointer to member access | Left-to-Right |
18 | . | Member access | Left-to-Right |
18 | -> | Pointer to member access | Left-to-Right |
17 | @ | Address of | Right-to-Left |
17 | * | Value of | Right-to-Left |
17 | New | Allocate Memory | Right-to-Left |
17 | Delete | Deallocate Memory | Right-to-Left |
16 | ^ | Exponentiate | Left-to-Right |
15 | - | Negate | Right-to-Left |
14 | * | Multiply | Left-to-Right |
14 | / | Divide | Left-to-Right |
13 | \ | Integer divide | Left-to-Right |
12 | MOD | Modulus | Left-to-Right |
11 | SHL | Shift left | Left-to-Right |
11 | SHR | Shift right | Left-to-Right |
10 | + | Add | Left-to-Right |
10 | - | Subtract | Left-to-Right |
9 | & | String concatenation | Left-to-Right |
8 | Is | Run-time type information check | N/A |
7 | = | Equal | Left-to-Right |
7 | <> | Not equal | Left-to-Right |
7 | < | Less than | Left-to-Right |
7 | <= | Less than or equal | Left-to-Right |
7 | >= | Greater than or equal | Left-to-Right |
7 | > | Greater than | Left-to-Right |
6 | NOT | Complement | Right-to-Left |
5 | AND | Conjunction | Left-to-Right |
4 | OR | Inclusive Disjunction | Left-to-Right |
3 | EQV | Equivalence | Left-to-Right |
3 | IMP | Implication | Left-to-Right |
3 | XOR | Exclusive Disjunction | Left-to-Right |
2 | ANDALSO | Short Circuit Conjunction | Left-to-Right |
2 | ORELSE | Short Circuit Inclusive Disjunction | Left-to-Right |
1 | =[>] | Assignment | Left-to-Right |
1 | &= | Concatenate and Assign | N/A |
1 | += | Add and Assign | N/A |
1 | -= | Subtract and Assign | N/A |
1 | *= | Multiply and Assign | N/A |
1 | /= | Divide and Assign | N/A |
1 | \= | Integer Divide and Assign | N/A |
1 | ^= | Exponentiate and Assign | N/A |
1 | MOD= | Modulus and Assign | N/A |
1 | AND= | Conjunction and Assign | N/A |
1 | EQV= | Equivalence and Assign | N/A |
1 | IMP= | Implication and Assign | N/A |
1 | OR= | Inclusive Disjunction and Assign | N/A |
1 | XOR= | Exclusive Disjunction and Assign | N/A |
1 | SHL= | Shift Left and Assign | N/A |
1 | SHR= | Shift Right and Assign | N/A |
1 | LET | Assignment | N/A |
lowest | LET() | Assignment | N/A |
Free Pascal
operator | precedence | category |
---|---|---|
not , unary + , unary - , @ , ** |
highest (first) | unary operators, power |
* , / , div , mod , and , shl , shr , as , << , >> , is [until FPC 3.3.1] |
second | multiplying operators |
+ , - , or , xor , ><
|
third | adding operators |
= , <> , < , > , <= , >= , in , is [since FPC 3.3.1]
|
lowest | relational operators |
“[B]inary operators of the same precedence are left-associative.” Nevertheless, “[t]he order in which expressions of the same precedence are evaluated is not guaranteed to be left-to-right.” (quotes from the Free Pascal Reference Guide)
The default configuration sets {$boolEval off}
({$B-}
for short).
This enables “lazy evaluation” and thus affects evaluation order.
One notable difference to standardized Pascal in operator precedence can be switched:
Normally, Free Pascal’s unary minus is at the highest precedence level.
With {$modeSwitch ISOUnaryMinus+}
, which is enabled by default in {$mode ISO}
and {$mode extendedPascal}
, unary minus can be put at the same level as all other adding operators (like the ISO standards define).
Furor
Furor is basically an "RPN-style" language. Thus, similarly to the Forth, Furor as the language of a stack machine does not require operator precedence. Since all arguments for operations are taken from the stack the order is simply left to right, in the order of the source code.
FutureBasic
When an expression includes more than one operator, the order in which the operations are performed can affect the result. When an operator appears to the left or right of a parenthetical expression, all of the operations within the parentheses are performed first. When several operators all appear within the same matching pair of parentheses (or outside of all parentheses), the order in which their operations are performed is determined by their order of precedence, with "higher precedence" operations being performed before "lower precedence" ones. For example, consider this expression: 4 + 7 * 5 The "*" operator has a higher precedence than the "+" operator (see the table below). So, when this expression is evaluated, first 7 is multiplied by 5 to get 35; then that result is added to 4 to get the final answer of 39. The following table lists the operators in order of their precedence, from highest to lowest. When an expression contains several operators at the same level of precedence (and within the same depth of parentheses), their operations are always performed from left to right.
Precedence | Operators |
---|---|
Highest | Unary operators: +, -, ^, *, /, \, \\, <, <=, >, >=, =, |
==, <>, !=, <<, >>, Not, Mod, And, Or, Xor, Nand, Nor | |
1 | unary "+", unary "-", Not |
2 | ^ |
3 | *, /, \, \\, Mod |
4 | + (addition), - (substraction) |
5 | <, <=, >, >=, =, ==, <>, !=, << (strings), >> (strings) |
6 | << (shift left), >> (shift right) |
7 | And, Or, Xor, Nand, Nor |
Go
Precedence | Operators |
---|---|
Highest | Unary operators: +, -, !, ^, *, &, <- |
5 | *, /, %, <<, >>, &, &^ |
4 | +, -, |, ^ |
3 | ==, !=, <, <=, >, >= |
2 | && |
1 | || |
Binary operators of the same precedence associate from left to right. Associativity has no meaning for unary operators.
Syntactic elements not in the list are not considered operators in Go; if they present ambiguity in order of evaluation, the ambiguity is resolved by other rules specific to those elements.
Haskell
Precedence | Operator | Description | Associativity |
---|---|---|---|
9
highest |
.
|
Function composition | Right |
8 | ^,^^,**
|
Power | Right |
7 | *,/,`quot`,`rem`,`div`,`mod`
|
Left | |
6 | +,-
|
Left | |
5 | :
|
Append to list | Right |
4 | ==,/=,<,<=,>=,>
|
Compare-operators | |
3 | &&
|
Logical AND | Right |
2 | ||
|
Logical OR | Right |
1 | >>,>>=
|
Left | |
1 | =<<
|
Right | |
0 | $,$!,`seq`
|
Right |
Icon and Unicon
Taken from http://www.cs.arizona.edu/icon/refernce/exprlist.htm#expressions (blank lines separate groups of operators with equal precedence):
(expr) # grouping {expr1;expr2;...} # compound x(expr1,expr2,...) # process argument list x{expr1,expr2,...} # process co-expression list [expr1,expr2,...] # list expr.F # field reference expr1[expr2] # subscript expr1[expr2,expr3,...] # multiple subscript expr1[expr2:expr3] # section expr1[expr2+:expr3] # section expr1[expr2-:expr3] # section not expr # success/failure reversal | expr # repeated alternation ! expr # element generation * expr # size + expr # numeric value - expr # negative . expr # value (dereference) / expr # null \ expr # non-null = expr # match and tab ? expr # random value ~ expr # cset complement @ expr # activation ^ expr # refresh expr1 \ expr2 # limitation expr1 @ expr2 # transmission expr1 ! expr2 # invocation expr1 ^ expr2 # power expr1 * expr2 # product expr1 / expr2 # quotient expr1 % expr2 # remainder expr1 ** expr2 # intersection expr1 + expr2 # sum expr1 - expr2 # numeric difference expr1 ++ expr2 # union expr1 -- expr2 # cset or set difference expr1 || expr2 # string concatenation expr1 ||| expr2 # list concatenation expr1 < expr2 # numeric comparison expr1 <= expr2 # numeric comparison expr1 = expr2 # numeric comparison expr1 >= expr2 # numeric comparison expr1 > expr2 # numeric comparison expr1 ~= expr2 # numeric comparison expr1 << expr2 # string comparison expr1 <<= expr2 # string comparison expr1 == expr2 # string comparison expr1 >>= expr2 # string comparison expr1 >> expr2 # string comparison expr1 ~== expr2 # string comparison expr1 === expr2 # value comparison expr1 ~=== expr2 # value comparison expr1 | expr2 # alternation expr1 to expr2 by expr3 # integer generation expr1 := expr2 # assignment expr1 <- expr2 # reversible assignment expr1 :=: expr2 # exchange expr1 <-> expr2 # reversible exchange expr1 op:= expr2 # (augmented assignments) expr1 ? expr2 # string scanning expr1 & expr2 # conjunction Low Precedence Expressions break [expr] # break from loop case expr0 of { # case selection expr1:expr2 ... [default:exprn] } create expr # co-expression creation every expr1 [do expr2] # iterate over generated values fail # failure of procedure if expr1 then exp2 [else exp3] # if-then-else next # go to top of loop repeat expr # loop return expr # return from procedure suspend expr1 [do expr2] # suspension of procedure until expr1 [do expr2] # until-loop while expr1 [do expr2] # while-loop
J
Precedence | Grammatical classification | Associativity |
---|---|---|
highest | conjunctions | long left scope |
adverbs | ||
lowest | verbs | long right scope |
See http://www.jsoftware.com/help/dictionary/partsofspeech.htm for tokens in each grammatical class.
Note that other parts of speech do not have any precedence, because they are not "operators".
Note that this is an imprecise statement of the grammatical rules. For a complete treatment, see http://www.jsoftware.com/help/dictionary/dicte.htm
Here's an informal treatment of the grammar:
Conjunctions require a left and right argument, either of which may be a noun or a verb. If one argument is omitted the conjunction is curried with the remaining argument, forming an adverb (if the right argument is omitted, the precedence of the conjunction is treated as lower than the precedence of a verb -- this might be thought of as a consequence of the "long left scope" of conjunctions extending as far as possible).
Adverbs require a single left argument, which may be a noun or a verb.
Verbs require a right argument which must be a noun and may accept an optional left argument (which must also be a noun). Unless we're working with a dangling (rightmost) conjunction, verbs have lower precedence than adverbs and conjunctions. (A conjunction on the far right without a right argument is treated as having lower precedence than verbs.) That said, note that the form verb verb verb
is legal - this creates a derived verb whose arguments are given to the left and right verb and their results will be the argument for the middle verb. Longer trains are treated by using this mechanism on the rightmost three verbs. A shorter train is also given special treatment (the right verb gets the right argument, the left verb gets a left argument and the result of the right verb).
Nouns are not operators and accept no arguments.
The result of a verb must be a noun.
The result of an adverb or a conjunction can have any one of these grammatical classifications, and verb results are typical (and, thus, the result of an adverb or a conjunction may accept further arguments). Adverbs and conjunctions serve a role analogous to that of macros in other languages.
Java
This is well-documented on the Oracle website.
JavaScript
Mozilla Developer Network have a nice list of this at JavaScript Reference:Expressions and operators:Operator Precedence
jq
The order of precedence of jq operators is shown in the following table, which also shows operator associativity:
- "%right" and %left" mean respectively right and left-associative;
- "%nonassoc" means it is a syntax error to find the operator twice in a row;
- "(none)" means that that no associativity is defined.
The associativity rules can be summarized:
- Operators with one of the characters "=", "<", or ">" in them are non-associative;
- "," and "//" are right-associative;
- All others are or behave as left-associative operators.
Precedence | Operator | Associativity | Description |
---|---|---|---|
lowest | %right | pipe | |
, | %left | generator | |
// | %right | specialized "or" for detecting empty streams | |
= += -= *= /= %= //= | %nonassoc | set component | |
or | %left | short-circuit "or" | |
and | %left | short-circuit "and" | |
!= == < > <= >= | %nonassoc | boolean tests | |
+ - | %left | polymorphic plus and minus | |
* / % | %left | polymorphic multiply, divide; mod | |
highest | ? | (none) | post-fix operator for suppressing errors (see note [1] below) |
Notes:
- If the expression immediately to the left of "?" raises an error, "?" suppresses it and emits nothings at all. E.g. 'error("bye")?' is equivalent to the expression 'empty'.
- Parentheses alter the order of evaluation in the usual way.
- Control structures such as if ... then ... else ... end and reduce ... as VAR (...; ...) determine the boundaries of subexpressions.
Julia
Julia Operators in Order of Preference -------------------------------------------- Syntax . followed by :: Exponentiation ^ Fractions // Multiplication * / % & \ Bitshifts << >> >>> Addition + - | ⊻ Syntax : .. followed by |> Comparisons > < >= <= == === != !== <: Control flow && followed by || followed by ? Assignments = += -= *= /= //= \= ^= ÷= %= |= &= ⊻= <<= >>= >>>= Operator precedence can be checked within Julia with the Base.operator_precedence function: julia> Base.operator_precedence(:>=), Base.operator_precedence(:&&), Base.operator_precedence(:(=)) (6, 4, 1) Julia Associativity of Operators --------------------------------------------- Assignment (=, etc.), conditional (a ? b : c), -> arrows, lazy OR/AND (&& ||), power operators, and unary operators are right associative. All others are left associative.
Kotlin
This is well-documented on the Kotlin language website.
Lambdatalk
As with Common Lisp and Scheme, Lambdatalk uses s-expressions so there is no need for operator precedence.
Such an expression "1+2*3+4" is written {+ 1 {* 2 3} 4}
LIL
From the LIL readme.txt documentation:
expr [...] combines all arguments into a single string and evaluates the mathematical expression in that string. The expression can use the following operators (in the order presented): (a) - parentheses -a - negative sign +a - positive sign ~a - bit inversion !a - logical negation a * b - multiplication a / b - floating point division a \ b - integer division a % b - modulo a + b - addition a - b - subtraction a << b - bit shifting a >> b a <= b - comparison a >= b a < b a > b a == b - equality comparison a != b a | b - bitwise OR a & b - bitwise AND a || b - logical OR a && b - logical AND
Lua
Table available here. That table does not contain all operators, however.
Precedence | Operator | Description |
---|---|---|
lowest | or | Boolean OR |
and | Boolean AND | |
<, <=, >, >=, ~=, == | Comparisons | |
.. | Concatenation [1] | |
+, - | Addition and subtraction | |
*, /, % | Multiplication, division, modulo | |
not, -, # | Boolean NOT, negation, length | |
^ | Exponentiation [1] | |
highest | x[index], x.index, x(arguments...), x:m(arguments...) | Generic index, string index, function call, method index+call [2] |
Notes:
- Concatenation and exponentiation are right-associative, all other binary operators are left-associative
- Binding is done at the call site; therefore, method lookup is syntactically part of the call
Mathematica /Wolfram Language
Here is an outline:
Precedence | Class | Examples |
---|---|---|
highest | Extensions of symbol names | x_, #2 , e::s, etc. |
Function application variants | e[e], e@@e, etc. | |
Power-related operators | √e, e^e, etc. | |
Multiplication-related operators | ∇e, e/e, e⊗e, e e, etc. | |
Addition-related operators | e⊕e, e+e, e⋃e, etc. | |
Relational operators | e==e, e∼e, e∈e, etc. | |
Arrow and vector operators | e↗e, e⇌e, etc. | |
Logic operators | e&&e, e∨e, e⊢e, etc. | |
Pattern and rule operators | e, e->e, e/.e, etc. | |
Pure function operator | e& | |
Assignment operators | e=e, e:=e, etc. | |
lowest | Compound expression | e;e |
There is a table of precedence of all operators on the page tutorial/OperatorInputForms in Mathematica help.
MATLAB
Here is an outline:
Precedence | Class | |
---|---|---|
highest | Parenthesis () | |
Transpose (.'), power (.^), complex conjugate transpose ('), matrix power (^) | ||
Unary plus (+), unary minus (-), logical negation (~) | ||
Multiplication (.*), right division (./), left division (.\), matrix multiplication (*), matrix right division (/), matrix left division (\) | ||
Addition (+), subtraction (-) | ||
Colon operator (:) | ||
Less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), equal to (==), not equal to (~=) | ||
Element-wise AND (&) | ||
Element-wise OR ( | )
| ||
Short-circuit AND (&&) | ||
Lowest | Short-circuit OR ( || )
|
There is a table of precedence of all operators on the page [6]
min
min is a stack language that uses postfix notation, so for the most part, all operators have the same precedence. Sigils are a small exception. However, they de-sugar to postfix. For example, the following two lines are equivalent:
42 :my-var
42 "my-var" define
Nim
Precedence | Operators | Relevant character |
---|---|---|
10 (highest) | $ , ^
| |
9 | * , / , div , mod , shl , shr , %
|
* , % , \ , /
|
8 | + , -
|
|
7 | &
|
&
|
6 | ..
|
.
|
5 | == , <= , < , >= , > , != , in , notin , is , isnot , not , of , as
|
= , < , > , !
|
4 | and
|
|
3 | or , xor
|
|
2 | @ , : , ?
| |
1 | assignment operator (like += , *= )
|
|
0 (lowest) | arrow like operator (like -> , => )
|
OCaml
This table contains the precedence and associativity of operators and other expression constructs in OCaml, including user-defined operators.
Oforth
Oforth uses RPN notation. There are not different operator precedences. Everything is evaluated left to right.
PARI/GP
Unless otherwise stated, operators at a given level are applied left-to-right.
Precedence | Operator | Description |
---|---|---|
highest | :
|
Type information for gp2c . Ignored by gp.
|
()
|
Postfix function call notation. | |
++ , --
|
Postfix increment or decrement operators. (Note that these work like the prefix ++ and -- operators in C.)
| |
. , [ ]
|
Member operator (as in m.mod ), selection operator (as in v[1] ).
| |
' , ~ , !
|
Postfix derivative, transpose, and factorial; prefix negation. | |
#
|
Prefix cardinality operator (like length() ).
| |
^
|
Infix exponentiation operator, evaluated right-to-left. | |
+ , - (unary)
|
Prefix sign operators. | |
* , / , % , \ , \/ , << , >>
|
Infix multiplication, division, modulus, integer division, rounded quotient, left shift, and right shift. | |
+ , -
|
Infix addition and subtraction. | |
< , <= , > , >= , != or <> , == , ===
|
Infix comparison operators. === tests whether two objects are identical component-wise and is stricter than == .
| |
&& , ||
|
Infix shortcut logical AND and OR. | |
= , += , -= , *= , %= , /= , \= , \/= , <<= , >>=
|
Infix assignment, evaluated right-to-left. | |
lowest | ->
|
Infix function definition. |
There are some exceptions to this standard order:
- If the short-circuit operator `&&` is used and the left expression is falsy (`0`, `[]`, etc.) then the right expression is not evaluated. Similarly, with `||` is the left is truthy then the right expression is not evaluated.
- Assignment and all of the compound assignment operators need an lvalue on the left; if there is an expression where the rightmost part is an lvalue, assignment happens first. So `1 + n = 4 + 1` first adds 4 to 1, then assigns 5 to n, then adds 1 to 5.
See the User's Guide to PARI/GP in the documentation, section 2.4, "GP operators".
Pascal
Standard Pascal, as laid out in ISO standard 7185, recognizes four precedence levels. Extended Pascal (EP), defined in ISO standard 10206, has one additional level, exponentiating operators. The following is a consolidated table for both standards:
class | operators |
---|---|
negation |
|
exponentiating operators |
|
multiplying operators |
|
adding operators |
|
relational operators |
|
“Sequences of two or more operators of the same precedence shall be left associative.” (quote from ISO standards)
However, unlike some other programming languages, operator precedence does not define evaluation order.
This is because Pascal does not permit “lazy evaluation”:
Except in the case of and_then
and or_else
, the evaluation order implementation-defined.
Some compilers, for instance the FPC (Free Pascal Compiler), evaluate “more complex” subexpression first before evaluating “easy” subexpressions (rationale: avoid register spilling).
Perl
See the relevant documentation for a table of Perl 5 operators ordered by precedence level.
Phix
Precedence | Operators |
---|---|
highest | parenthesis/function/type calls/ternary operator |
subscripts/slices . | |
unary- unary+ not ~ | |
* / | |
+ - | |
<< >> | |
& | |
&& || | |
< > <= >= | |
= != | |
and or xor | |
lowest | { , , , } |
Parenthesis is required to mix and/or/xor in an expression, without said you get a compilation error because the compiler refuses to guess what you actually mean.
Perhaps surprisingly Phix does not rely on associativity, mainly because it has a power() function rather than an infix operator for that.
You could alternatively say that all the above operators bar the unary ops are left associative, within their own precedence level.
Phix has reference counting with copy-on-write semantics: technically parameters are always passed by reference, which can improve performance, however attempting to modify anything with a reference count greater than one performs an internal clone (at that level) which means it behaves as if everything were being passed by value.
It also has automatic pass by reference for local variables such that (eg) table = somefunc(table)
does not increase the reference count (in practice the calling code's local variable becomes unassigned over the call) and consequently makes in-situ modification possible, which can obviously also significantly benefit performance.
Under "with js", aka "with javascript_semantics", any said internal clone triggers a runtime error, effectively prohibiting copy-on-write semantics and thus ensuring the code is compatible with JavaScript, and in fact also implicitly banning the usual pass-by-sharing semantics of JavaScript, except where covered by the automatic pbr handling.
PHP
PicoLisp
There is no need to worry about operator precedence in PicoLisp and Lisp's in general. All operators are normal functions and all of the code is organized as S-expressions with a prefixed polish notation.
PL/I
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | exponentiation | ** | from right to left |
1 | unary operators | - + | from right to left |
1 | logical NOT | ¬ | from right to left |
2 | arithmetic * / | * / | from left to right |
3 | arithmetic + - | + - | from left to right |
4 | concatenation | || | from left to right |
5 | comparison | = ¬= > < >= <= | from left to right |
6 | logical AND | & | from left to right |
7 | logical OR | | | from left to right |
lowest |
PureBasic
Arguments are passed by value.
Priority | Operator | Description | Associativity | Arity |
---|---|---|---|---|
highest | grouping | '(' ')' |
||
8 | bitwise NOT, negation | '~' '-' |
Right to Left | 1 |
7 | arithmetic shift left, bitwise modulo, bitwise OR | '<<' '>>' '%' '!' |
Left to Right | 2 |
6 | bitwise OR, bitwise AND | ' '&' | Left to Right | 2 |
5 | multiplication, division | '*' '/' |
Left to Right | 2 |
4 | addition, subtraction, string concatenation | '+' '-' '+' |
Left to Right | 2 |
3 | comparative | '>' '>=' '=>' '<' |
Left to Right | 2 |
2 | logical | 'Not' |
Right to Left | 1 |
1 | logical | 'And' 'Or' 'XOr' |
Left to Right | 2 |
lowest |
Python
See this table and the whole page for details on Python version 3.x An excerpt of which is this table:
Precedence | Operator | Description |
---|---|---|
lowest | lambda | Lambda expression |
if – else | Conditional expression | |
or | Boolean OR | |
and | Boolean AND | |
not x | Boolean NOT | |
in, not in, is, is not, <, <=, >, >=, !=, == | Comparisons, including membership tests and identity tests, | |
| | Bitwise OR | |
^ | Bitwise XOR | |
& | Bitwise AND | |
<<, >> | Shifts | |
+, - | Addition and subtraction | |
*, /, //, % | Multiplication, division, remainder [1] | |
+x, -x, ~x | Positive, negative, bitwise NOT | |
** | Exponentiation [2] | |
x[index], x[index:index], x(arguments...), x.attribute | Subscription, slicing, call, attribute reference | |
highest | (expressions...), [expressions...], {key:datum...}, {expressions...} | Binding or tuple display, list display, dictionary display, set display |
- Footnotes
- The
%
operator is also used for string formatting; the same precedence applies. - The power operator
**
binds less tightly than an arithmetic or bitwise unary operator on its right, that is,2**-1
is0.5
.
Q
Operators have equal precedence and expressions are evaluated from right to left.
q)3*2+1
9
q)(3*2)+1 / Brackets give the usual order of precedence
7
q)x:5
q)(x+5; x:20; x-5)
25 20 0
Quackery
Because Quackery uses postfix notation and relies entirely on fixed-argument function composition, all operators have the same precedence. Think of using a calculator that uses reverse-polish notation. Instead of writing (3+5)*2, you'd write 3 5 + 2 *. There is no need for parentheses to clarify the order of operations.
Racket
Racket uses S-expr for its syntax, operators and functions show no precedences as all code is written as:
(function arguments ...)
function being any function or operator (language or user defined) and arguments are the arguments passed to it.
Raku
(formerly Perl 6) See this table for a list of the precedence levels. Raku is an operator-rich language (and users may define more operators at will), so instead of listing all the operators in the table, representative operators are listed for some of the precedence levels; see later in the same file for a more complete list of predefined operators at each precedence level.
REALbasic
All operators are left-associated except exponentiation and Pair creation which are right-associated. Operators of the same scope and precedence will be evaluated from left-to-right. Precedence can be overridden by using parentheses, such that a + b - c <> a + (b - c).
By default, intrinsic types (Integer, String, Double, etc.) are passed by value and complex types (objects, arrays, etc.) are passed by reference. This can be overridden by using the ByVal or ByRef keyword before the parameter name in the method signature.
Operator(s) | Arity | Associativity | Description |
---|---|---|---|
. (dot) | 2 | Left | Scope resolution |
AddressOf, WeakAddressOf | 1 | Left | Delegate creation |
IsA, Is | 2 | Left | Compare an object reference to a class or interface name; Compare the operands to determine whether they are references to the same object |
^ | 2 | Right | Exponentiation |
- | 1 | Left | Negation and unary minus |
Not | 1 | Left | Logical not |
* / \ Mod | 2 | Left | Multiplication; floating-point division; integer division; modulo |
+, - | 2 | Left | Addition and string concatenation; subtraction |
=, <, >, <>, <=, >= | 2 | Left | Equal (comparison and assignment); less-than; greater-than; not equal; less-than or equal; greater-than or equal |
And | 2 | Left | Logical and bitwise And |
Or, Xor | 2 | Left | Logical and bitwise Or; logical and bitwise Exclusive-Or |
: (colon) | 2 | Right | Pair (e.g. linked-list) creation |
REXX
Arguments are passed by value.
╔══════════════════════════════════════════════════════════════════════╗ ║ ║ ║ The following is a table that lists the precedence and associativity ║ ║ of all the operators in the (classic) REXX language. ║ ║ ║ ║ 1 is the highest precedence. ║ ║ ║ ╠══════════╤════════╤══════════════════════════════════════════════════╣ ║ │ │ ║ ║precedence│operator│ description ║ ║ │ │ ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 1 │ - │ unary minus ║ ║ │ + │ unary plus ║ ║ │ \ │ logical not ║ ║ │ ├──(the following aren't supported by all REXXes)──╢ ║ │ ¬ │ logical not ║ ║ │ ~ │ logical not ║ ║ │ ^ │ logical not ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 2 │ ** │ exponentiation (integer power) ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 3 │ * │ multiplication ║ ║ │ / │ division ║ ║ │ % │ integer division ║ ║ │ // │ modulus (remainder division, sign of dividend)║ ║ │ / / │ modulus (any 2 or 3 character operators may ║ ║ │ │ have whitespace between characters.) ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 4 │ + │ addition ║ ║ │ - │ subtraction ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 5 │ || │ concatenation ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 6 │ & │ logical AND ║ ║ │ | │ logical OR (inclusive OR) ║ ║ │ && │ logical XOR (exclusive OR) ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 7 │[blank] │ concatenation ║ ║ │abuttal │ concatenation ║ ╟──────────┼────────┼──────────────────────────────────────────────────╢ ║ 8 │ = │ equal to ║ ║ │ == │ exactly equal to (also, strictly equal to) ║ ║ │ \= │ not equal to ║ ║ │ <> │ not equal to (also, less than or greater than) ║ ║ │ >< │ not equal to (also, greater than or less than) ║ ║ │ > │ greater than ║ ║ │ >= │ greater than or equal to ║ ║ │ < │ less than ║ ║ │ <= │ less than or equal to ║ ║ │ >> │ exactly greater than ║ ║ │ << │ exactly less than ║ ║ │ <<= │ exactly less than or equal to ║ ║ │ >>= │ exactly greater than or equal to ║ ║ │ ├──(the following aren't supported by all REXXes)──╢ ║ │ /= │ not equal to ║ ║ │ ¬= │ not equal to ║ ║ │ ~= │ not equal to ║ ║ │ ^= │ not equal to ║ ║ │ /== │ not exactly equal to ║ ║ │ \== │ not exactly equal to ║ ║ │ ¬== │ not exactly equal to ║ ║ │ ~== │ not exactly equal to ║ ║ │ ^== │ not exactly equal to ║ ║ │ /< │ not less than ║ ║ │ ~< │ not less than ║ ║ │ ¬< │ not less than ║ ║ │ ^< │ not less than ║ ║ │ /> │ not greater than ║ ║ │ ¬> │ not greater than ║ ║ │ ~> │ not greater than ║ ║ │ ^> │ not greater than ║ ║ │ /<= │ not less than or equal to ║ ║ │ ¬<= │ not less than or equal to ║ ║ │ ~<= │ not less than or equal to ║ ║ │ ^<= │ not less than or equal to ║ ║ │ />= │ not greater than or equal to ║ ║ │ ¬>= │ not greater than or equal to ║ ║ │ ~>= │ not greater than or equal to ║ ║ │ ^>= │ not greater than or equal to ║ ║ │ \>> │ not exactly greater than ║ ║ │ ¬>> │ not exactly greater than ║ ║ │ ~>> │ not exactly greater than ║ ║ │ ^>> │ not exactly greater than ║ ║ │ \<< │ not exactly less than ║ ║ │ ¬<< │ not exactly less than ║ ║ │ ~<< │ not exactly less than ║ ║ │ ^<< │ not exactly less than ║ ╚══════════╧════════╧══════════════════════════════════════════════════╝
Ring
The next table present operators from higher precedence (Evaluated first) to lower precedence.
Operator
. [] () {}
- ~ :Literal [list items]
++ - -
Start:End
* / %
+ -
<< >>
&
| ^
< > <= >=
= !=
not
and or
Assignment = += -= *= /= %=>>= <<= &= ^= |=
Example:
See 3+5*4 # prints 23
Ruby
Ruby operators, by precedence (high to low), with arity (N), associativity (A), and definability (D)
Operator(s) | N | A | D | Operation |
---|---|---|---|---|
! ~ + | 1 | R | Y | Boolean NOT, bitwise complement, unary plus |
** | 2 | R | Y | Exponentiation |
- | 1 | R | Y | Unary minus (define with -@) |
* / % | 2 | L | Y | Multiplication, division, modulo (remainder) |
+ - | 2 | L | Y | Addition (or concatenation), subtraction |
<< >> | 2 | L | Y | Bitwise shift-left (or append), bitwise shift-right |
& | 2 | L | Y | Bitwise AND |
| ^ | 2 | L | Y | Bitwise OR, bitwise XOR |
< <= >= > | 2 | L | Y | Ordering |
== === != =~ !~ <=> | 2 | N | Y | Equality, pattern matching, comparison |
&& | 2 | L | N | Boolean AND |
|| | 2 | L | N | Boolean OR |
.. ... | 2 | N | N | Range creation and Boolean flip-flops |
? : | 3 | R | N | Conditional |
rescue | 2 | L | N | Exception-handling modifier |
= **= *= / = %= += -= <<= >>= &&= &= ^= | 2 | R | N | Assignment |
defined? | 1 | N | N | Test variable definition and type |
not | 1 | R | N | Boolean NOT (low precedence) |
and or | 2 | L | N | Boolean AND, Boolean OR (low precedence) |
if unless while until | 2 | N | N | Conditional and loop modifiers |
Scala
Operator precedence is well-documented on the official Scala Documentation | Tour of Scala | Operators web page.
Scheme
As with Common Lisp and Racket, Scheme uses s-expressions so there is no need for operator precedence.
e.g. an expression like "3 + 4 x 5" must be entered as either (+ 3 (* 4 5))
or (* (+ 3 4) 5)
Scilab
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | transpose | ' |
|
2 | power | ** ^ |
right |
3 | multiplication & division | * / \ |
left |
4 | unary operator (opposite) | + - |
left |
5 | addition & subtraction | + - |
left |
6 | comparison | == ~= > < >= <= |
left |
7 | logical NOT | ~ |
left |
8 | logical AND | and |
left |
9 | logical OR | or xor |
left |
lowest |
Seed7
Seed7 supports user defined operators with priority and associativity. This includes user defined operator symbols. Priority and associativity are defined with the Seed7 Structured Syntax Description (S7SSD) A S7SSD statement like
$ syntax expr: .(). + .() is -> 7;
specifies the syntax of the +
operator.
The right arrow ->
describes the associativity:
Binding of operands from left to right. With 7
the priority
of the +
operator is defined. The syntax pattern
.(). + .()
is introduced and delimited with dots (.
). Without dots the pattern is
() + ()
The symbol ()
is a nonterminal symbol and +
is a terminal symbol.
The S7SSD does not distinguish between different nonterminal symbols.
Instead it only knows one nonterminal symbol: ()
.
The include file syntax.s7i contains the syntax of the predefined operators. The table below is extracted from syntax.s7i:
Priority | infix/prefix | Left associative | Right associative | Not associative |
---|---|---|---|---|
1 | infix | conv varConv cast value parse | ||
1 | prefix | { | getfunc getobj [ | |
2 | infix | . [ ^ -> | ||
3 | prefix | & | ||
4 | infix | ! | ** | |
4 | prefix | ! | ||
5 | prefix | + - conj | ||
6 | infix | * / div rem mdiv mod | ||
7 | infix | + - | ||
8 | infix | mult find | times | |
9 | infix | << >> | ||
10 | infix | & | ||
11 | infix | |||
12 | infix | = <> < > <= >= in not in | ||
13 | prefix | new sub | not subtype subrange set array hash | |
14 | infix | and | ||
15 | infix | or | ||
16 | infix | val radix RADIX digits sci | ||
17 | infix | exp lpad rpad lpad0 | ||
18 | infix | <& | ||
20 | infix | := +:= -:= *:= /:= <<:= >>:= &:= @:= |
Sidef
All operators in Sidef have the same precedence, which is controlled by lack of whitespace between the operands.
For example:
1+2 * 3+4 # means: (1+2) * (3+4)
See also the documentation on the precedence of operators.
Simula
Modern Simula syntax:
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | power | ** |
left |
2 | unary operator (opposite) | + - |
left |
3 | multiplication & division | * / // |
left |
4 | addition & subtraction | + - |
left |
5 | comparison | = <> < <= > >= |
left |
6 | logical NOT | NOT |
left |
7 | logical AND | AND |
left |
8 | logical OR | OR |
left |
9 | equivalence | EQUIV |
left |
10 | implication | IMPL |
left |
lowest |
Note: // is the Euclidean division
Smalltalk
Smalltalk does not have operators which are built in to the language.
All operations are message sends to a receiver object (aka virtual function calls).
Messages are one of 3 types:
unary message: no argument, alphanumeric name (highest precedence; left to right evaluation)
binary message: any combination of special characters (left to right evaluation)
keyword message: one or more arguments, alphanumeric name with colons (lowest precedence)
Unary message examples:
negated abs conjugated size isZero
Binary examples:
+ - * % <=> ===> ˜˜ ˜= = , ,,
(yes "," (comma) and ",," are possible!)
Keyword examples:
min: max: at: at:put: from:to:do: bitAnd: bitOr:
Within unary and binary messages, evaluation is strictly left to right. Keyword messages must be parenthesized.
No table can be presented here: there are too many such operators, and they can also be freely added by the programmer (i.e. you may define your own "Number fooBar" or "Number +-+-+ arg" messages (if it makes any sense to you).
Math expressions are usually parenthesized for better readability (by beginners):
5 + b negated. "same as 5 + (b negated); unary > binary"
a abs - b sqrt "same as (a abs) - (b sqrt); unary > binary"
a bitAnd:1+a abs. "same as a bitAnd:(1+(a abs)); unary > binary > keyword"
(a bitAnd:1+a) bitOr:(b bitAnd:1+2 abs). "ditto"
"Beginners might be confused by:"
5 + a * b "same as (5 + a) * b; all binary; therefore left to right"
Standard ML
Precedence | Operator | Associativity |
---|---|---|
highest | ||
7 | * / div mod
|
left |
6 | + - ^
|
left |
5 | :: @
|
right |
4 | = <> > >= < <=
|
left |
3 | := o
|
left |
0 | before
|
left |
Tcl
Tcl only supports operators within an expression context (such as the expr
command, which lists the operators with more detail):
Precedence | Operator | Description |
---|---|---|
highest | - + ~ ! | Unary minus, unary plus, bit-wise NOT, logical NOT. |
** | Exponentiation. Right-to-left associative. | |
* / % | Multiply, divide, remainder. | |
+ - | Add and subtract. | |
<< >> | Left and right shift. | |
< > <= >= | Boolean less, greater, less than or equal, and greater than or equal. | |
== != | Boolean equal and not equal. | |
eq ne | Boolean string equal and string not equal. | |
in ni | List containment and negated list containment. | |
& | Bit-wise AND. | |
^ | Bit-wise exclusive OR. | |
| | Bit-wise OR. Valid for integer operands only. | |
&& | Logical AND. Evaluates its second operand lazily. | |
|| | Logical OR. Evaluates its second operand lazily. | |
lowest | x ? y : z | If-then-else, as in C. Evaluates its second and third operands lazily. |
TI-83 BASIC
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | function | √( e^( 10^( sin( ... | |
2 | unary right operator | ² ! | left to right |
3 | exponentiation | ^ | left to right |
4 | unary left operator | (-) | right to left |
5 | permutation combination | nPr nCr | left to right |
6 | arithmetic * / | × ÷ | left to right |
7 | arithmetic + - | + - | left to right |
8 | relation | = ≠ > < ≥ ≤ | left to right |
9 | logical AND | and | left to right |
10 | logical OR | or xor | left to right |
11 | conversion | ►Frac ►Dec ... | left to right |
lowest |
note: no operator between 2 symbols means an implied multiplication, so priority 6
and left to right associativity
note: NOT is not an operator, it is a function: not()
Examples:
-2^2=-(2^2)=-4 2^3^2=(2^3)^2=64 4/2π=(4/2)π=2π=6.283185307 -B/2A=-((B/2)*A)=-(B/2)*A
VBScript
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | unary operator (opposite) | + - |
left |
2 | power | ^ |
left |
3 | multiplication & division | * / |
left |
4 | integer division | \ |
left |
5 | modulus | mod |
left |
6 | addition & subtraction | + - |
left |
7 | concatenation | & |
left |
8 | comparison | = <> < <= > >= Is |
left |
9 | logical NOT | Not |
left |
10 | logical AND | And |
left |
11 | logical OR | Or |
left |
12 | logical exclusion | Xor |
left |
13 | equivalence | Eqv |
left |
14 | implication | Imp |
left |
lowest |
Let's not the difference with Visual Basic on unary operator priority.
Example:
-2^2=(-2)^2=4 2^3^2=(2^3)^2=64
Visual Basic
Priority | Description | Operators | Associativity |
---|---|---|---|
highest | |||
1 | power | ^ |
left |
2 | unary operator (opposite) | + - |
left |
3 | multiplication & division | * / |
left |
4 | integer division | \ |
left |
5 | modulus | mod |
left |
6 | addition & subtraction | + - |
left |
7 | concatenation | & |
left |
8 | bit shift | << >> |
left |
9 | comparison | = <> < <= > >= Is IsNot Like |
left |
10 | logical NOT | Not |
left |
11 | logical AND | And AndAlso |
left |
12 | logical OR | Or OrElse |
left |
13 | logical XOR | Xor |
left |
lowest |
Visual Basic .NET
See Visual Basic
Note: the Imp and Eqv VB6 operators were been removed from Visual Basic .NET.
Wren
The following table is reproduced from the language documentation.
Arguments are passed by value though where the argument is a reference (anything other than numbers, booleans or null) this will, of course, copy the reference and not the data it refers to.
Prec | Operator | Description | Associates |
---|---|---|---|
1 | () [] . | Grouping, Subscript, Method call | Left |
2 | - ! ~ | Negate, Not, Complement | Right |
3 | * / % | Multiply, Divide, Modulo | Left |
4 | + - | Add, Subtract | Left |
5 | .. ... | Inclusive range, Exclusive range | Left |
6 | << >> | Left shift, Right shift | Left |
7 | & | Bitwise and | Left |
8 | ^ | Bitwise xor | Left |
9 | | | Bitwise or | Left |
10 | < <= > >= | Comparison | Left |
11 | is | Type test | Left |
12 | == != | Equals, Not equal | Left |
13 | && | Logical and | Left |
14 | || | Logical or | Left |
15 | ?: | Conditional | Right |
16 | = | Assignment, Setter | Right |
XPL0
All operations of equal precedence are evaluated (associate) left-to-right.
Precedence | Operator | Description |
---|---|---|
highest | () , | Grouping, comma separator (constructs) |
- + addr @ | Unary minus, unary plus, address of a variable | |
<< >> ->> | Left and right logical shifts, arithmetic shift right | |
* / | Multiply and divide | |
+ - | Add and subtract | |
= # < <= > >= | Comparisons: equal, not equal, less than, etc. | |
~ not | Bitwise NOT | |
& and | Bitwise AND | |
! or | xor | Bitwise OR and exclusive OR | |
lowest | if-then-else | If expression |
zkl
All operations of equal precedence are evaluated (associate) left-to-right. If shared with C it has the same precedence except for logical and/or, which have the same precedence.
Precedence | Operator | Description |
---|---|---|
highest | () .(dot) [], | Grouping/function call, .resolve, subscripting |
- not | Unary minus, logical not | |
* / % | Multiply, divide and modulo | |
+ - | Add and subtract | |
< <= > >= | Comparisons: equal, not equal, less than, etc. | |
== != | Comparisons: equal, not equal | |
and or | logical AND and logical OR | |
: | compose (nest expressions) | |
lowest | := = | Assignment |
- Programming Tasks
- Solutions by Programming Task
- Simple
- WikipediaSourced
- 11l
- 8th
- 6502 Assembly
- Ada
- ALGOL 60
- ALGOL 68
- ALGOL W
- AppleScript
- Arturo
- AWK
- BASIC256
- Bc
- BCPL
- BQN
- Bracmat
- C
- C++
- C sharp
- Caché ObjectScript
- Clojure
- COBOL
- Common Lisp
- D
- Delphi
- Eiffel
- Erlang
- F Sharp
- Factor
- Forth
- Fortran
- FreeBASIC
- Free Pascal
- Furor
- FutureBasic
- Go
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Lambdatalk
- LIL
- Lua
- Mathematica
- Wolfram Language
- MATLAB
- Min
- Nim
- OCaml
- Oforth
- PARI/GP
- Pascal
- Perl
- Phix
- Phix/basics
- PHP
- PicoLisp
- PL/I
- PureBasic
- Python
- Q
- Quackery
- Racket
- Raku
- REALbasic
- REXX
- Ring
- Ruby
- Scala
- Scheme
- Scilab
- Seed7
- Sidef
- Simula
- Smalltalk
- Standard ML
- Tcl
- TI-83 BASIC
- VBScript
- Visual Basic
- Visual Basic .NET
- Wren
- XPL0
- Zkl