This article needs additional citations for verification .(January 2019) |
In computer programming, an operator is a programming language construct that provides functionality that may not be possible to define as a user-defined function (i.e. sizeof in C) or has syntax different than a function (i.e. infix addition as in a+b
). Some languages allow a language-defined operator to be overridden with user-defined behavior and some allow for user-defined operator symbols.
Some operators are represented with symbols – characters typically not allowed for a function identifier. For example, a function that tests for greater-than could be named gt
, but many languages provide an infix symbolic operator so that code looks more familiar. For example, this:
if gt(x, y) then return
Can be:
if x > y then return
Operators may also differ semantically from functions. For example, short-circuit Boolean operations evaluate later arguments only if earlier ones are not false.
Many operators differ syntactically from user-defined functions. In most languages, a function is prefix notation with fixed precedence level and associativity and often with compulsory parentheses (e.g. Func(a)
or (Func a)
in Lisp). In contrast, many operators are infix notation and involve different use of delimiters such as parentheses.
In general, an operator may be prefix, infix, postfix, matchfix, circumfix or bifix [1] [2] [3] [4] [5] , and the syntax of an expression involving an operator depends on its arity (number of operands), precedence, and (if applicable), associativity. Most programming languages support binary operators and a few unary operators, with a few supporting more operands, such as the ?: operator in C, which is ternary. There are prefix unary operators, such as unary minus -x
, and postfix unary operators, such as post-increment x++
; and binary operations are infix, such as x + y
or x = y
. Infix operations of higher arity require additional symbols, such as the ternary operator ?: in C, written as a ? b : c
– indeed, since this is the only common example, it is often referred to as the ternary operator. Prefix and postfix operations can support any desired arity, however, such as 1 2 3 4 +
.
The semantics of operators particularly depends on value, evaluation strategy, and argument passing mode (such as Boolean short-circuiting). Simply, an expression involving an operator is evaluated in some way, and the resulting value may be just a value (an r-value), or may be an object allowing assignment (an l-value).
In simple cases this is identical to usual function calls; for example, addition x + y
is generally equivalent to a function call add(x, y)
and less-than comparison x < y
to lt(x, y)
, meaning that the arguments are evaluated in their usual way, then some function is evaluated and the result is returned as a value. However, the semantics can be significantly different. For example, in assignment a = b
the target a
is not evaluated, but instead its location (address) is used to store the value of b
– corresponding to call-by-reference semantics. Further, an assignment may be a statement (no value), or may be an expression (value), with the value itself either an r-value (just a value) or an l-value (able to be assigned to). As another example, the scope resolution operator :: and the element access operator . (as in Foo::Bar
or a.b
) operate not on values, but on names, essentially call-by-name semantics, and their value is a name.
Use of l-values as operator operands is particularly notable in unary increment and decrement operators. In C, for instance, the following statement is legal and well-defined, and depends on the fact that array indexing returns an l-value:
x=++a[i];
An important use is when a left-associative binary operator modifies its left argument (or produces a side effect) and then evaluates to that argument as an l-value. [a] This allows a sequence of operators all affecting the original argument, allowing a fluent interface, similar to method cascading. A common example is the <<
operator in the C++ iostream
library, which allows fluent output, as follows:
cout<<"Hello"<<" "<<"world!"<<endl;
Some languages (e.g. C, C++ and PHP) define a fixed set of operators, while others (e.g. Prolog, [6] Seed7, [7] F#, OCaml, Haskell) allow for user-defined operators. Some programming languages restrict operator symbols to special characters like + or := while others allow names like div
(e.g. Pascal).
Most languages do not support user-defined operators since the feature significantly complicates parsing. [b] Many languages only allow operators to be used for built-in types, but some allow operators to be overloaded for user-defined types. Some languages allow new operators to be defined which may involve meta-programming (specifying the operators in a separate language). Definition of new operators, particularly runtime definition, often makes correct static analysis of programs impossible, since the syntax of the language may be Turing-complete, so even constructing the syntax tree may require solving the halting problem, which is impossible. This occurs for Perl, for example, and some dialects of Lisp.
Conceptually, an operator can be overloaded in the same way that a function can – acting differently based on the type of input. Some languages provide operators that are inherently overloaded (aka ad hoc polymorphic). For example, in Java the +
operator sums numbers or concatenates strings. Some languages support user-defined operator overloading (such as C++).
Some languages implicitly convert (aka coerce) operands to be compatible with each other. For example, Perl coercion rules cause 12 + "3.14"
to evaluate to 15.14
. The string literal "3.14"
is converted to the numeric value 3.14 before addition is applied. Further, 3.14
is treated as floating point so the result is floating point even though 12
is an integer literal. JavaScript follows different rules so that the same expression evaluates to "123.14"
since 12
is converted to a string which is then concatenated with the second operand.
In general, a programmer must be aware of the specific rules regarding operand coercion in order to avoid unexpected and incorrect behavior.
Examples of infix operators include:
a+b
a>b
a AND b
or a&&b
a=b
or a:=b
a.b
a::b
or a.b
Less common operators include:
e, f
*p
and address-of operator: &x
number = spell_out_numbers ? "forty-two" : 42
x ?: y
x ?? y
x <=> y
+=
, -=
, *=
, /=
, %=
, <<=
, >>=
, &=
, ^=
, |=
Similarly, some digital signal processors provide special opcodes for fused operations like multiply–accumulate (MAC/MAD) or fused multiply–add (FMA) and some high-performance software libraries support functions like cis x = cos x + i sin x to boost processing speed or reduce code size.The following table shows the operator features in several programming languages:
Language | Symbolic operators | Alphanumeric operators | Prefix | Infix | Postfix | Precedence | Associativity | Overloading | User-defined overloading | User-defined symbols |
---|---|---|---|---|---|---|---|---|---|---|
ALGOL 68 each symbolic operator has an alphanumeric equivalent and some a non-ASCII equivalent | +* ** * / % %* %× - + < <= >= > = /= & -:= +:= *:= /:= %:= %*:= +=: :=: :/=: non-ASCII: | not abs arg bin entier leng level odd repr round shorten i shl shr up down lwb upb lt le ge gt eq ne and or over mod elem minusab plusab timesab divab overab modab plusto is isnt | Yes | Yes | No | Yes (prefix operators always have priority 10) | Infix operators are left associative, prefix operators are right associative | Yes | Yes | Yes |
APL | + - × ÷ ⌈ ⌊ * ⍟ <nowiki>|</nowiki> ! ○ ~ ∨ ∧ ⍱ ⍲ < ≤ = ≥ > ≠ . @ ≡ ≢ ⍴ , ⍪ ⍳ ↑ ↓ ? ⍒ ⍋ ⍉ ⌽ ⊖ ∊ ⊥ ⊤ ⍎ ⍕ ⌹ ⊂ ⊃ ∪ ∩ ⍷ ⌷ ∘ → ← / ⌿ \ ⍀ ¨ ⍣ & ⍨ ⌶ ⊆ ⊣ ⊢ ⍠ ⍤ ⌸ ⌺ ⍸ | (requires ⎕ prefix) | Yes (first-order functions only) | Yes | Yes (higher-order functions only) | Higher-order functions precede first-order functions | Higher-order functions are left associative, first-order functions are right associative | Yes | Yes | Yes (alphanumeric only) |
B | () [] ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ <nowiki>|</nowiki> [[?:]] = =+ =- =* =/ =% =& =^ =<nowiki>|</nowiki> [8] | Yes | Yes | Yes | Yes | Yes | No | No | No | |
C | () [] -> . ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ <nowiki>|</nowiki> && <nowiki>||</nowiki> [[?:]] = += -= *= /= %= &= ^= | sizeof | Yes | Yes | Yes | Yes | Yes | Yes | No | No |
C++ | (same as C) | (same as C plus) typeid new delete throw decltype static_cast dynamic cast reinterpret_cast const_cast | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
C# | (same as C plus) ?. ?[] ?? ??= | sizeof nameof new stackalloc await throw checked unchecked is as delegate default true false LINQ: from select where group...by group...by...into join...in...on...equals join...in...on...equals...into orderby orderby...descending Roslyn-only: __makeref __refvalue __reftype | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
Java | (same as C) | new throw instanceof | Yes | Yes | Yes | Yes | Yes | Yes | No | No |
Eiffel | [] + - * / // = /= | not and or implies "and then" "or else" | Yes | Yes | No | Yes | Yes | No | Yes | Yes |
Haskell | + - * / ^ ^^ ** == /= > < >= <= && || >>= >> $ $! . ++ !! : (and many more) | (function name must be in backticks) | Yes | Yes | No | Yes | Yes | Yes, using Type classes | Yes | |
Pascal | * / + - = < > <> <= >= := | not div mod and or in | Yes | Yes | No | Yes | Yes | Yes | No | No |
Perl | -> ++ -- ** ! ~ \ + - . =~ !~ * / % < > <= >= == != <=> ~~ & | ^ &&|| ' | print sort chmod chdir rand and or not xor lt gt le ge eq ne cmp x | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
PHP | [] ** ++ -- ~ @! [9] * / % + - . << >> < <= > >= == != === !== <> <=> & ^ | && || ?? ?: = += -= *= **= /= .= %= &= |= ^= <<= >>= | clone new unset print echo isset instanceof and or xor | Yes | Yes | Yes | Yes | Yes | No | No | No |
PL/I | ( ) -> + - * / ** > ¬> >= = ¬= <= < ¬< ¬ &||| | Yes | Yes | No | Yes | Yes | No | No | No | |
Prolog | :- ?- ; , . =.. = \= < =< >= > == \== - + / * | spy nospy not is mod | Yes | Yes | Yes | Yes | Yes | No | No | Yes |
Raku | ++ -- ** ! ~ ~~ * / + - . < > <= >= == != <=> & | ^ &&|| // [10] | print sort chmod chdir rand and or not xor lt gt le ge eq ne leg cmp x xx | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes [11] |
Seed7 | {} [] -> ** ! + - * / << >> & >< | = <> > >= < <= <& := +:= -:= *:= /:= <<:= >>:= &:= @:= | conv varConv parse conj div rem mdiv mod times mult in not and or digits lpad rpad lpad0 | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |
Smalltalk | (up to two characters [12] ) | (alphanumeric symbols need a colon suffix) | No | Yes | Yes | No | No | Yes | Yes | Yes |
Swift | (any Unicode symbol string except) . (including) ! ~ + - * / % =+ =- =* =/ =% &+ &- &* =&+ =&- =&* && || << >> & | ^ == != < <= > >= ?? ... ..< | is as as? | Yes | Yes | Yes | Yes (defined as partial order in precedence groups) | Yes (defined as part of precedence groups) | Yes | Yes | Yes |
Visual Basic .NET | () . ! ?() ?. ?! + - * / \ & << >> < <= > >= ^ <> = += -= *= /= \= &= ^= <<= >>= | New Await Mod Like Is IsNot Not And AndAlso Or OrElse Xor If(...,...) If(...,...,...) GetXmlNamespace(...) GetType(...) NameOf(...) TypeOf...Is TypeOf...IsNot DirectCast(...,...) TryCast(...,...) LINQ: From Aggregate...Into Select Distinct Where <Order By>...[Ascending|Descending] Take <Take While> Skip <Skip While> Let Group...By...Into Join...On <Group Join...On...Into> | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
@
requires lexing and tokenizing this character, and the phrase structure (syntax tree) depends on the arity and precedence of this operator.In logic, disjunction, also known as logical disjunction or logical or or logical addition or inclusive disjunction, is a logical connective typically notated as and read aloud as "or". For instance, the English language sentence "it is sunny or it is warm" can be represented in logic using the disjunctive formula , assuming that abbreviates "it is sunny" and abbreviates "it is warm".
First-order logic—also called predicate logic, predicate calculus, quantificational logic—is a collection of formal systems used in mathematics, philosophy, linguistics, and computer science. First-order logic uses quantified variables over non-logical objects, and allows the use of sentences that contain variables. Rather than propositions such as "all men are mortal", in first-order logic one can have expressions in the form "for all x, if x is a man, then x is mortal"; where "for all x" is a quantifier, x is a variable, and "... is a man" and "... is mortal" are predicates. This distinguishes it from propositional logic, which does not use quantifiers or relations; in this sense, propositional logic is the foundation of first-order logic.
In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on.
In computer programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.
Polish notation (PN), also known as normal Polish notation (NPN), Łukasiewicz notation, Warsaw notation, Polish prefix notation or simply prefix notation, is a mathematical notation in which operators precede their operands, in contrast to the more common infix notation, in which operators are placed between operands, as well as reverse Polish notation (RPN), in which operators follow their operands. It does not need any parentheses as long as each operator has a fixed number of operands. The description "Polish" refers to the nationality of logician Jan Łukasiewicz, who invented Polish notation in 1924.
In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.
In mathematics, a unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function , where A is a set; the function is a unary operation on A.
Infix notation is the notation commonly used in arithmetical and logical formulae and statements. It is characterized by the placement of operators between operands—"infixed operators"—such as the plus sign in 2 + 2.
In mathematics, a ternary operation is an n-ary operation with n = 3. A ternary operation on a set A takes any given three elements of A and combines them to form a single element of A.
In programming languages, scientific calculators and similar common operator notation or operator grammar is a way to define and analyse mathematical and other formal expressions. In this model a linear sequence of tokens are divided into two classes: operators and operands.
This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.
In logic, a truth function is a function that accepts truth values as input and produces a unique truth value as output. In other words: the input and output of a truth function are all truth values; a truth function will always output exactly one truth value, and inputting the same truth value(s) will always output the same truth value. The typical example is in propositional logic, wherein a compound statement is constructed using individual statements connected by logical connectives; if the truth value of the compound statement is entirely determined by the truth value(s) of the constituent statement(s), the compound statement is called a truth function, and any logical connectives used are said to be truth functional.
In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, conditional expression, ternary if, or inline if. An expression if a then b else c
or a ? b : c
evaluates to b
if the value of a
is true, and otherwise to c
. One can read it aloud as "if a then b otherwise c". The form a ? b : c
is the most common, but alternative syntax do exist; for example, Raku uses the syntax a ?? b !! c
to avoid confusion with the infix operators ?
and !
, whereas in Visual Basic .NET, it instead takes the form If(a, b, c)
.
In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities.
The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972.
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.
In mathematics, an operation is a function from a set to itself. For example, an operation on real numbers will take in real numbers and return a real number. An operation can take zero or more input values to a well-defined output value. The number of operands is the arity of the operation.
The null coalescing operator is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, such as : C# since version 2.0, Dart since version 1.12.0, PHP since version 7.0.0, Perl since version 5.10 as logical defined-or, PowerShell since 7.0.0, and Swift as nil-coalescing operator.
The syntax and semantics of Prolog, a programming language, are the sets of rules that define how a Prolog program is written and how it is interpreted, respectively. The rules are laid out in ISO standard ISO/IEC 13211 although there are differences in the Prolog implementations.
Increment and decrement operators are unary operators that increase or decrease their operand by one.
{{cite book}}
: |journal=
ignored (help)CS1 maint: date and year (link)