This articleneeds additional citations forverification. Please helpimprove this article byadding citations to reliable sources. Unsourced material may be challenged and removed. Find sources: "Operator" computer programming – news ·newspapers ·books ·scholar ·JSTOR(January 2019) (Learn how and when to remove this message) |
Incomputer programming, anoperator is aprogramming language construct that provides functionality that may not be possible to define as a user-definedfunction (e.g.sizeof inC) or hassyntax different from that of a function (e.g.infix addition as ina+b). Like other programming language concepts,operator has a generally accepted, although debatable, meaning among practitioners.[clarification needed]
Some operators are represented with symbols – characters typically not allowed for a functionidentifier – to allow for presentation that is more familiar looking than typical function syntax. For example, a function that tests for greater-than could be namedgt, 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.
Many operators differ syntactically from user-defined functions. In most languages, a function isprefix notation with fixedprecedence level and associativity and often with compulsoryparentheses (e.g.Func(a) or(Func a) inLisp). 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 anexpression involving an operator depends on itsarity (number ofoperands), precedence, and (if applicable),associativity. Most programming languages supportbinary operators and a fewunary 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 aspost-incrementx++; and binary operations are infix, such asx + y orx = y. Infix operations of higher arity require additional symbols, such as theternary operator ?: in C, written asa ? b : c – indeed, since this is the only common example, it is often referred to asthe ternary operator. Prefix and postfix operations can support any desired arity, however, such as1 2 3 4 +.
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 functionadd(x, y) in that the arguments are evaluated and then the functional behavior is applied. However,assignment is different. For example, givena = b the targeta isnot evaluated. Instead its value is replaced with the value ofb. Thescope resolution and element access operators (as inFoo::Bar anda.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, theincrement operator reads the element value of an array and then assigns the element value.
++a[i];
The C++<< operator allows forfluent syntax by supporting a sequence of operators that affect a single argument. For example:
cout<<"Hello"<<" "<<"world!"<<endl;
Some languages provide operators that aread hoc polymorphic – inherently overloaded. For example, inJava the+ operator sumsnumbers orconcatenatesstrings.
Some languages support user-definedoverloading (such asC++ andFortran). An operator, defined by the language, can beoverloaded to behave differently based on the type of input.
Some languages (e.g. C, C++ andPHP) define a fixed set of operators, while others (e.g.Prolog,[6]F#,OCaml,Haskell) allow for user-defined operators. Some programming languages restrict operator symbols to special characters like+ or:= while others allow names likediv (e.g.Pascal), and even arbitrary names (e.g.Fortran where an upto 31 character long operator name is enclosed between dots[7]).
Most languages do not support user-defined operators since the feature significantly complicates parsing. Introducing a new operator changes the arity and precedencelexical specification of the language, which affects phrase-levellexical analysis. Custom operators, particularly via runtime definition, often make correctstatic 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 forPerl, for example, and some dialects ofLisp.
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.
Some languages implicitly convert (akacoerce) operands to be compatible with each other. For example,Perl coercion rules cause12 + "3.14" to evaluate to15.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 though12 is an integer literal.JavaScript follows different rules so that the same expression evaluates to"123.14" since12 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.
a+ ba> baAND b ora&& ba= b ora:= bx<=> ya.ba::b ora.bcondition? a: bx?: yx?? y&x*pe, f+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=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 68each 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 | + - × ÷ ⌈ ⌊ * ⍟ | ! ○ ~ ∨ ∧ ⍱ ⍲ < ≤ = ≥ > ≠ . @ ≡ ≢ ⍴ , ⍪ ⍳ ↑ ↓ ? ⍒ ⍋ ⍉ ⌽ ⊖ ∊ ⊥ ⊤ ⍎ ⍕ ⌹ ⊂ ⊃ ∪ ∩ ⍷ ⌷ ∘ → ← / ⌿ \ ⍀ ¨ ⍣ & ⍨ ⌶ ⊆ ⊣ ⊢ ⍠ ⍤ ⌸ ⌺ ⍸ | (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 | () [] ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ | ?: = =+ =- =* =/ =% =& =^ =| =<< =>> === =|= =< => =<= =>=[8][9] | Yes | Yes | Yes | Yes | Yes | No | No | No | |
| C | () [] -> . ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>= | sizeof | Yes | Yes | Yes | Yes | Yes | Yes | No | No |
| C++ | (same as C) | (same as C plus)typeidnewdeletethrowdecltypestatic_castdynamic castreinterpret_castconst_cast | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
| C# | (same as C plus)?. ?[]?? ??= | sizeof nameof new stackalloc awaitthrow checked unchecked is as delegate default true falseLINQ: from select where group...by group...by...into join...in...on...equals join...in...on...equals...into orderby orderby...descendingRoslyn-only: __makeref __refvalue __reftype | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
| Java | (same as C) | newthrowinstanceof | 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, usingType classes | Yes | |
| mvBasic Databasic/Unibasic | + - * / ^ ** : = ! & [] += -= := # < > <= >= <> >< =< #> => #< | AND OR NOT EQ NE LT GT LE GE MATCH ADDS() ANDS() CATS() DIVS() EQS() GES() GTS() IFS() | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
| Pascal | * / + - = < > <> <= >= := | notdivmodandor 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 | [] ** ++ -- ~ @![10] * / % + - . << >> < <= > >= == != === !== <><=> & ^ | && ||???: = += -= *= **= /= .= %= &= |= ^= <<= >>= | clone new unset print echo issetinstanceofandorxor | 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 | ++ -- ** ! ~ ~~ * / + - . < > <= >= == != <=> & | ^ && || //[11] | 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[12] |
| Rust | () [] . ! + - * & ? / % << >> < <= > >= == != ^ | && || .. ..= = += -= *= /= %= &= ^= |= <<= >>=[13] | &mut&raw const&raw mutas[13] | Yes | Yes | Yes | Yes | Yes | Yes | Yes | No |
| Smalltalk | (up to two characters[14]) | (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 |
| Zig | () [] {} . ! ~ + +% +| - -% -| * *% *| & / % << <<| >> < <= > >= == != ^ | ++ ** .* .? = += +%= +|= -= -%= -|= *= *%= *|= /= %= &= ^= |= <<= <<|= >>=[15] | and or orelse catch[15] | Yes | Yes | Yes | Yes | Yes | Yes | No | No |