Compound Operation (computer Programming)
   HOME

TheInfoList



OR:

In
computer programming Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, an operator is a
programming language A programming language is a system of notation for writing computer programs. Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
construct that provides functionality that may not be possible to define as a user-defined function (i.e.
sizeof sizeof is a unary operator in the C and C++ programming languages that evaluates to the storage size of an expression or a data type, measured in units sized as char. Consequently, the expression sizeof(char) evaluates to 1. The number of b ...
in C) or has
syntax In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituenc ...
different than a function (i.e.
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 ...
addition as in a+b). Like other programming language concepts, ''operator'' has a generally accepted, although debatable meaning among practitioners while at the same time each language gives it specific meaning in that context, and therefore the meaning varies by language. Some operators are represented with symbols characters typically not allowed for a function
identifier 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, person, physical countable object (or class thereof), or physical mass ...
to allow for presentation that is more familiar looking than typical function syntax. 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 Some languages allow a language-defined operator to be overridden with user-defined behavior and some allow for user-defined operator symbols. Operators may also differ semantically from functions. For example, short-circuit Boolean operations evaluate later arguments only if earlier ones are not false.


Differences from functions


Syntax

Many operators differ syntactically from user-defined functions. In most languages, a function is
prefix notation Polish notation (PN), also known as normal Polish notation (NPN), Łukasiewicz notation, Warsaw notation, Polish prefix notation, Eastern Notation or simply prefix notation, is a mathematical notation in which operators ''precede'' their oper ...
with fixed precedence level and associativity and often with compulsory parentheses (e.g. Func(a) or (Func a) in
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
). 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 A circumfix ( abbr: ) (also parafix, confix, or ambifix) is an affix which has two parts, one placed at the start of a word, and the other at the end. Circumfixes contrast with prefixes, attached to the beginnings of words; suffixes, attached a ...
or bifix, and the syntax of an expression involving an operator depends on its
arity 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 ...
(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. Unknown operands in equalities of expressions can be found by equation solving. Example The following arithmetic expres ...
s), precedence, and (if applicable),
associativity In mathematics, the associative property is a property of some binary operations that rearranging the parentheses in an expression will not change the result. In propositional logic, associativity is a Validity (logic), valid rule of replaceme ...
. Most programming languages support
binary operator 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, a binary operation o ...
s 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 ...
?: 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 +.


Semantics

The semantics of an operator may significantly differ from that of a normal function. For reference, addition is evaluated like a normal function. For example, x + y can be equivalent to a function add(x, y) in that the arguments are evaluated and then the functional behavior is applied. However, assignment is different. For example, given a = b the target a is ''not'' evaluated. Instead its value is replaced with the value of b. The scope resolution and element access operators (as in Foo::Bar and a.b, respectively, in the case of e.g. C++) operate on identifier names; not values. In C, for instance, the array indexing operator can be used for both read access as well as assignment. In the following example, the increment operator reads the element value of an array and then assigns the element value. ++a The C++ << operator allows for fluent syntax by supporting a sequence of operators that affect a single argument. For example: cout << "Hello" << " " << "world!" << endl;


ad hoc polymorphic

Some languages provide operators that are ad hoc polymorphic inherently overloaded. For example, in
Java Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
the operator sums
number A number is a mathematical object used to count, measure, and label. The most basic examples are the natural numbers 1, 2, 3, 4, and so forth. Numbers can be represented in language with number words. More universally, individual numbers can ...
s or
concatenate 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 formalizations of concatenati ...
s strings.


Customization

Some languages support user-defined overloading (such as C++ and Fortran). An operator, defined by the language, can be overloaded to behave differently based on the type of input. Some languages (e.g. C, C++ and PHP) define a fixed set of operators, while others (e.g.
Prolog Prolog is a logic programming language that has its origins in artificial intelligence, automated theorem proving, and computational linguistics. Prolog has its roots in first-order logic, a formal logic. Unlike many other programming language ...
, Seed7, F#,
OCaml OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
,
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 pioneered several programming language ...
) 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), and even arbitrary names (e.g. Fortran where an upto 31 character long operator name is enclosed between dots). Most languages do not support user-defined operators since the feature significantly complicates parsing. Introducing a new operator changes the arity and precedence lexical specification of the language, which affects phrase-level
lexical analysis Lexical tokenization is conversion of a text into (semantically or syntactically) meaningful ''lexical tokens'' belonging to categories defined by a "lexer" program. In case of a natural language, those categories include nouns, verbs, adjectives ...
. Custom operators, particularly via runtime definition, often make correct static analysis of a program 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 high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
, for example, and some dialects of
Lisp Lisp (historically LISP, an abbreviation of "list processing") is a family of programming languages with a long history and a distinctive, fully parenthesized Polish notation#Explanation, prefix notation. Originally specified in the late 1950s, ...
. If a language does allow for defining new operators, the mechanics of doing so may involve meta-programming specifying the operator in a separate language.


Operand coercion

Some languages implicitly convert (aka coerce) operands to be compatible with each other. For example,
Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language". Perl was developed ...
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 JavaScript (), often abbreviated as JS, is a programming language and core technology of the World Wide Web, alongside HTML and CSS. Ninety-nine percent of websites use JavaScript on the client side for webpage behavior. Web browsers have ...
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

;Mathematical operators *
Arithmetic Arithmetic is an elementary branch of mathematics that deals with numerical operations like addition, subtraction, multiplication, and division. In a wider sense, it also includes exponentiation, extraction of roots, and taking logarithms. ...
: such as addition, a b * Relational: such as greater than, a b *
Logic Logic is the study of correct reasoning. It includes both formal and informal logic. Formal logic is the study of deductively valid inferences or logical truths. It examines how conclusions follow from premises based on the structure o ...
: such as a b or a b * Assignment: such as a b or a b * Three-way comparison (aka spaceship): x y ;Program structure operators * 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 a ...
field access: such as ab * Scope resolution: such as ab or ab ;Conditional operators * Ternary conditional: condition a b * Elvis: x y * Null coalesing: x y ;Notable C and C++ operators * Address-of operator: x *
Dereference In computer science, a pointer is an object (computer science), object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped I/O, memo ...
: p *
Comma The comma is a punctuation mark that appears in several variants in different languages. Some typefaces render it as a small line, slightly curved or straight, but inclined from the vertical; others give it the appearance of a miniature fille ...
: e f ;Compound operators * Compound assignment (aka augmented assignment) in C/C++: +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, , = * Fused: such as


Operator features in programming languages

The following table shows the operator features in several programming languages:


See also

*
Operators in C and C++ This is a list of operators in the C and C++ programming languages. All listed operators are in C++ and lacking indication otherwise, in C as well. Some tables include a "In C" column that indicates whether an operator is also in C. Note tha ...


References

{{reflist Programming constructs