In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, operators are constructs defined within
programming languages
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
which behave generally like
functions, but which differ
syntactically or
semantically
Semantics (from grc, σημαντικός ''sēmantikós'', "significant") is the study of reference, meaning, or truth. The term can be used to refer to subfields of several distinct disciplines, including philosophy, linguistics and comput ...
.
Common simple examples include arithmetic (e.g. addition with ), comparison (e.g. "
greater than
In mathematics, an inequality is a relation which makes a non-equal comparison between two numbers or other mathematical expressions. It is used most often to compare two numbers on the number line by their size. There are several different n ...
" with
>
), and
logical
Logic is the study of correct reasoning. It includes both formal and informal logic. Formal logic is the science of deductively valid inferences or of logical truths. It is a formal science investigating how conclusions follow from premises ...
operations (e.g.
AND
, also written
&&
in some languages). More involved examples include
assignment
Assignment, assign or The Assignment may refer to:
* Homework
* Sex assignment
* The process of sending National Basketball Association players to its development league; see
Computing
* Assignment (computer science), a type of modification to ...
(usually
=
or
:=
),
field
Field may refer to:
Expanses of open ground
* Field (agriculture), an area of land used for agricultural purposes
* Airfield, an aerodrome that lacks the infrastructure of an airport
* Battlefield
* Lawn, an area of mowed grass
* Meadow, a grass ...
access in a record or
object
Object may refer to:
General meanings
* Object (philosophy), a thing, being, or concept
** Object (abstract), an object which does not exist at any particular time or place
** Physical object, an identifiable collection of matter
* Goal, an ...
(usually
.
), and the
scope resolution operator
In computer programming, scope is an enclosing context where values and expressions are associated. The scope resolution operator helps to identify and specify the context to which an identifier refers, particularly by specifying a namespace. Th ...
(often
::
or
.
). Languages usually define a set of built-in operators, and in some cases allow users to add new meanings to existing operators or even define completely new operators.
Syntax
Syntactically operators usually contrast to
functions. In most languages, functions may be seen as a special form of prefix operator with fixed
precedence level and associativity, often with compulsory
parentheses
A bracket is either of two tall fore- or back-facing punctuation marks commonly used to isolate a segment of text or data from its surroundings. Typically deployed in symmetric pairs, an individual bracket may be identified as a 'left' or 'r ...
e.g.
Func(a)
(or
(Func a)
in
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
). Most languages support programmer-defined functions, but cannot really claim to support programmer-defined operators, unless they have more than prefix notation and more than a single precedence level. Semantically operators can be seen as special form of function with different calling notation and a limited number of parameters (usually 1 or 2).
The position of the operator with respect to its operands may be
prefix
A prefix is an affix which is placed before the Word stem, stem of a word. Adding it to the beginning of one word changes it into another word. For example, when the prefix ''un-'' is added to the word ''happy'', it creates the word ''unhappy'' ...
,
infix
An infix is an affix inserted inside a word stem (an existing word or the core of a family of words). It contrasts with ''adfix,'' a rare term for an affix attached to the outside of a stem, such as a prefix or suffix.
When marking text for int ...
or
postfix, and the syntax of an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
involving an operator depends on its
arity
Arity () is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named ''rank'', but this word can have many other meanings in mathematics. In ...
(number of
operand
In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on.
Example
The following arithmetic expression shows an example of operators and operands:
:3 + 6 = 9
In the above examp ...
s), precedence, and (if applicable),
associativity
In mathematics, the associative property is a property of some binary operations, which means that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a valid rule of replacement f ...
. Most programming languages support
binary operators
In mathematics, a binary operation or dyadic operation is a rule for combining two elements (called operands) to produce another element. More formally, a binary operation is an operation of arity two.
More specifically, an internal binary ope ...
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 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 computer science, a ternary operator i ...
?: 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 +
.
Occasionally parts of a language may be described as "matchfix" or "circumfix" operators, either to simplify the language's description or implementation. A circumfix operator consists of two or more parts which enclose its operands. Circumfix operators have the highest precedence, with their contents being evaluated and the resulting value used in the surrounding expression. The most familiar circumfix operator are the parentheses mentioned above, used to indicate which parts of an expression are to be evaluated before others. Another example from physics is the
inner product
In mathematics, an inner product space (or, rarely, a Hausdorff space, Hausdorff pre-Hilbert space) is a real vector space or a complex vector space with an operation (mathematics), operation called an inner product. The inner product of two ve ...
notation of Dirac's
bra–ket notation. Circumfix operators are especially useful to denote operations that involve many or varying numbers of operands.
The specification of a language will specify the syntax the operators it supports, while languages such as
Prolog
Prolog is a logic programming language associated with artificial intelligence and computational linguistics.
Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
that support programmer-defined operators require that the syntax be defined by the programmer.
Semantics
The semantics of operators particularly depends on value, evaluation strategy, and argument passing mode (such as boolean short-circuiting). Simply, an
expression
Expression may refer to:
Linguistics
* Expression (linguistics), a word, phrase, or sentence
* Fixed expression, a form of words with a specific meaning
* Idiom, a type of fixed expression
* Metaphorical expression, a particular word, phrase, o ...
involving an operator is evaluated in some way, and the resulting
value
Value or values may refer to:
Ethics and social
* Value (ethics) wherein said concept may be construed as treating actions themselves as abstract objects, associating value to them
** Values (Western philosophy) expands the notion of value beyo ...
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
In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
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
In computer programming, scope is an enclosing context where values and expressions are associated. The scope resolution operator helps to identify and specify the context to which an identifier refers, particularly by specifying a namespace. Th ...
:: and the element access operator . (as in
Foo::Bar
or
a.b
) operate not on values, but on ''names'', essentially
call-by-name
In a programming language, an evaluation strategy is a set of rules for evaluating expressions. The term is often used to refer to the more specific notion of a ''parameter-passing strategy'' that defines the kind of value that is passed to the f ...
semantics, and their value is a name.
Use of l-values as operator operands is particularly notable in unary
increment and decrement operators
Increment and decrement operators are unary operators that ''add'' or ''subtract'' one, to or from their operand, respectively.
They are commonly implemented in imperative programming languages. C-like languages feature two versions (pre- an ...
. 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
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. This allows a sequence of operators all affecting the original argument, allowing a
fluent interface
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric ...
, similar to
method cascading In object-oriented programming, method cascading is syntax which allows multiple methods to be called on the same object. This is particularly applied in fluent interfaces.
For example, in Dart, the cascade:
a..b()
..c();
is equivalent to the in ...
. A common example is the
<<
operator in the C++
iostream
In the C++ programming language, input/output library refers to a family of class templates and supporting functions in the C++ Standard Library that implement stream-based input/output capabilities. It is an object-oriented alternative to C's F ...
library, which allows fluent output, as follows:
cout << "Hello" << " " << "world!" << endl;
User-defined operators
A language may contain a fixed number of built-in operators (e.g. , etc. in
C and C++,
PHP
PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
), or it may allow the creation of programmer-defined operators (e.g.
Prolog
Prolog is a logic programming language associated with artificial intelligence and computational linguistics.
Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
,
Seed7
Seed7 is an extensible general-purpose programming language designed by Thomas Mertes. It is syntactically similar to Pascal and Ada. Along with many other features, it provides an extension mechanism. Daniel Zingaro"Modern Extensible Languages" ...
,
F#,
OCaml
OCaml ( , formerly Objective Caml) is a general-purpose programming language, general-purpose, multi-paradigm programming language which extends the Caml dialect of ML (programming language), ML with object-oriented programming, object-oriented ...
,
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
). Some programming languages restrict operator symbols to special characters like or while others allow also names like
div
(e.g.
Pascal
Pascal, Pascal's or PASCAL may refer to:
People and fictional characters
* Pascal (given name), including a list of people with the name
* Pascal (surname), including a list of people and fictional characters with the name
** Blaise Pascal, Fren ...
).
Most languages have a built-in set of operators, but do not allow user-defined operators, as this significantly complicates parsing. Many languages only allow operators to be used for built-in types, but others allow existing operators to be used for user-defined types; this is known as
operator overloading
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 ...
. Some languages allow new operators to be defined, however, either at compile time or at run time. This may involve meta-programming (specifying the operators in a separate language), or within the language itself. Definition of new operators, particularly runtime definition, often makes correct
static analysis
Static analysis, static projection, or static scoring is a simplified analysis wherein the effect of an immediate change to a system is calculated without regard to the longer-term response of the system to that change. If the short-term effect i ...
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
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, for example, and some dialects of
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
.
Examples
Common examples that differ syntactically are mathematical
arithmetic operation
Arithmetic () is an elementary part of mathematics that consists of the study of the properties of the traditional operations on numbers—addition, subtraction, multiplication, division, exponentiation, and extraction of roots. In the 19th cen ...
s, e.g. ">" for "
greater than
In mathematics, an inequality is a relation which makes a non-equal comparison between two numbers or other mathematical expressions. It is used most often to compare two numbers on the number line by their size. There are several different n ...
", with names often outside the language's set of
identifiers
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, physical countable object (or class thereof), or physical noncountable ...
for functions, and called with a syntax different from the language's syntax for calling functions. As a function, "greater than" would generally be named by an identifier, such as
gt
or
greater_than
and called as a function, as
gt(x, y)
. Instead, the operation uses the special character
>
(which is tokenized separately during
lexical analysis
In computer science, lexical analysis, lexing or tokenization is the process of converting a sequence of characters (such as in a computer program or web page) into a sequence of ''lexical tokens'' ( strings with an assigned and thus identified ...
), and infix notation, as
x > y
.
Common examples that differ semantically (by argument passing mode) are boolean operations, which frequently feature
short-circuit evaluation
A short circuit (sometimes abbreviated to short or s/c) is an electrical circuit that allows a current to travel along an unintended path with no or very low electrical impedance. This results in an excessive current flowing through the circuit. ...
: e.g. a short-circuiting conjunction (X AND Y) that only evaluates later arguments if earlier ones are not false, in a language with strict call-by-value functions. This behaves instead similarly to if/then/else.
Less common operators include:
*
Comma operator
In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type); there i ...
:
e, f
*
Dereference operator
In computer programming, the dereference operator or indirection operator, sometimes denoted by "*" (i.e. an asterisk), is a unary operator (i.e. one with a single operand) found in C-like languages that include pointer variables. It operates ...
:
*p
and address-of operator:
&x
*
?: or ternary operator:
number = spell_out_numbers ? "forty-two" : 42
**
Elvis operator
In certain computer programming languages, the Elvis operator, often written ?:, is a binary operator that returns its first operand if that operand evaluates to a true value, and otherwise evaluates and returns its second operand. This is identic ...
:
x ?: y
*
Null coalescing operator
The null coalescing operator (called the Logical Defined-Or operator in Perl) is a binary operator that is part of the syntax for a basic conditional expression in several programming languages, including C#, PowerShell as of version 7.0.0, Perl a ...
:
x ?? y
*
Spaceship operator
In computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy.
Machine ...
(for
three-way comparison
In computer science, a three-way comparison takes two values A and B belonging to a type with a total order and determines whether A < B, A = B, or A > B in a single operation, in accordance with the mathematical law of trichotomy.
Machine ...
):
x <=> y
Compilation
A compiler can implement operators and functions with
subroutine calls or with
inline code. Some built-in operators supported by a language have a direct mapping to a small number of
instructions
Instruction or instructions may refer to:
Computing
* Instruction, one operation of a processor within a computer architecture instruction set
* Computer program, a collection of instructions
Music
* Instruction (band), a 2002 rock band from Ne ...
commonly found on
central processing units, though others (''e.g.'' '+' used to express
string concatenation
In formal language theory and computer programming, string concatenation is the operation of joining character strings end-to-end. For example, the concatenation of "snow" and "ball" is "snowball". In certain formalisations of concatenat ...
) may have complicated implementations.
Operator overloading
In some programming languages an operator may be ''ad hoc polymorphic'', that is, have definitions for more than one kind of data, (such as in
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's List ...
where the operator is used both for the addition of numbers and for the concatenation of strings). Such an operator is said to be ''overloaded''. In languages that support operator overloading by the programmer (such as
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
) but have a limited set of operators, operator overloading is often used to define customized uses for operators.
In the example
IF ORDER_DATE > "12/31/2011" AND ORDER_DATE < "01/01/2013" THEN CONTINUE ELSE STOP
, the operators are: ">" (greater than), "AND" and "<" (less than).
Operand coercion
Some languages also allow for the operands of an operator to be implicitly converted, or ''
coerced
Coercion () is compelling a party to act in an involuntary manner by the use of threats, including threats to use force against a party. It involves a set of forceful actions which violate the free will of an individual in order to induce a desi ...
'', to suitable data types for the operation to occur. For example, in
Perl
Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
coercion rules lead into
12 + "3.14"
producing the result of
15.14
. The text
"3.14"
is converted to the number 3.14 before addition can take place. Further,
12
is an integer and
3.14
is either a floating or fixed-point number (a number that has a decimal place in it) so the integer is then converted to a floating point or fixed-point number respectively.
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
follows opposite rules—finding the same expression above, it will convert the integer
12
into a string
"12"
, then concatenate the two operands to form
"123.14"
.
In the presence of coercions in a language, the programmer must be aware of the specific rules regarding operand types and the operation result type to avoid subtle programming mistakes.
Operator features in programming languages
The following table shows the operator features in several programming languages:
See also
*
Relational operator
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 (''e.g.'', ) and inequalities (''e.g.'', ).
In prog ...
Notes
References
{{reflist
Programming constructs