Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Operator (computer programming)

From Wikipedia, the free encyclopedia
Basic programming language construct
icon
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)
This article is about operators in computer programming. For other uses, seeOperator (disambiguation).

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.

Differences from functions

[edit]

Syntax

[edit]

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 +.

Semantics

[edit]

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;

ad hoc polymorphic

[edit]
Further information:Ad hoc polymorphism

Some languages provide operators that aread hoc polymorphic – inherently overloaded. For example, inJava the+ operator sumsnumbers orconcatenatesstrings.

Customization

[edit]

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.

Operand coercion

[edit]
Further information:Type conversion

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.

Examples

[edit]
See also:Category:Operators (programming)
Mathematical operators
Program structure operators
Conditional operators
Notable C and C++ operators

Compound operators

Operator features in programming languages

[edit]

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

LanguageSymbolic operatorsAlphanumeric 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+* ** * / % %* %× - + &lt; &lt;= >= > = /= & -:= +:= *:= /:= %:= %*:= +=: :=: :/=:

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 isntYesYesNoYes(prefix operators always have priority 10)Infix operators are left associative, prefix operators are right associativeYesYesYes
APL+ - × ÷ ⌈ ⌊ * ⍟ | ! ○ ~ ∨ ∧ ⍱ ⍲ &lt; ≤ = ≥ > ≠ . @ ≡ ≢ ⍴ , ⍪ ⍳ ↑ ↓ ? ⍒ ⍋ ⍉ ⌽ ⊖ ∊ ⊥ ⊤ ⍎ ⍕ ⌹ ⊂ ⊃ ∪ ∩ ⍷ ⌷ ∘ → ← / ⌿ \ ⍀ ¨ ⍣ & ⍨ ⌶ ⊆ ⊣ ⊢ ⍠ ⍤ ⌸ ⌺ ⍸(requires ⎕ prefix)Yes(first-order functions only)YesYes(higher-order functions only)Higher-order functions precede first-order functionsHigher-order functions are left associative, first-order functions are right associativeYesYesYes(alphanumeric only)
B() [] ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ | ?: = =+ =- =* =/ =% =& =^ =| =<< =>> === =|= =< => =<= =>=[8][9]YesYesYesYesYesNoNoNo
C() [] -> . ! ~ ++ -- + - * & / % << >> < <= > >= == != ^ | && || ?: = += -= *= /= %= &= ^= |= <<= >>=sizeofYesYesYesYesYesYesNoNo
C++(same as C)(same as C plus)typeidnewdeletethrowdecltypestatic_castdynamic castreinterpret_castconst_castYesYesYesYesYesYesYesNo
C#(same as C plus)?. ?[]?? ??=sizeof nameof new stackalloc awaitthrow 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
YesYesYesYesYesYesYesNo
Java(same as C)newthrowinstanceofYesYesYesYesYesYesNoNo
Eiffel[] + - * / // = /=not and or implies "and then" "or else"YesYesNoYesYesNoYesYes
Haskell+ - * / ^ ^^ ** == /= > < >= <= && || >>= >> $ $! . ++ !! :(and many more)(function name must be in backticks)YesYesNoYesYesYes, usingType classesYes
mvBasic Databasic/Unibasic+ - * / ^ ** : = ! & [] += -= := # < > <= >= <> >< =< #> => #<AND OR NOT EQ NE LT GT LE GE MATCH ADDS() ANDS() CATS() DIVS() EQS() GES() GTS() IFS()YesYesYesYesYesYesYesNo
Pascal* / + - = < > <> <= >= :=notdivmodandor inYesYesNoYesYesYesNoNo
Perl-> ++ -- ** ! ~ \ + - . =~ !~ * / % < > <= >= == != <=> ~~ & | ^ && || ' '' // .. ... ?: = += -= *= , =>print sort chmod chdir rand and or not xor lt gt le ge eq ne cmp xYesYesYesYesYesYesYesNo
PHP[] ** ++ -- ~ @![10] * / % + - . << >> < <= > >= == != === !== <><=> & ^ | && ||???: = += -= *= **= /= .= %= &= |= ^= <<= >>=clone new unset print echo issetinstanceofandorxorYesYesYesYesYesNoNoNo
PL/I( ) -> + - * / ** > ¬> >= = ¬= <= < ¬< ¬ & | ||YesYesNoYesYesNoNoNo
Prolog:- ?- ; , . =.. = \= < =< >= > == \== - + / *spy nospy not is modYesYesYesYesYesNoNoYes
Raku++ -- ** ! ~ ~~ * / + - . < > <= >= == != <=> & | ^ && || //[11]print sort chmod chdir rand and or not xor lt gt le ge eq ne leg cmp x xxYesYesYesYesYesYesYesYes[12]
Rust() [] . ! + - * & ? / % << >> < <= > >= == != ^ | && || .. ..= = += -= *= /= %= &= ^= |= <<= >>=[13]&mut&raw const&raw mutas[13]YesYesYesYesYesYesYesNo
Smalltalk(up to two characters[14])(alphanumeric symbols need a colon suffix)NoYesYesNoNoYesYesYes
Swift(any Unicode symbol string except). (including)! ~ + - * / % =+ =- =* =/ =% &+ &- &* =&+ =&- =&* && || << >> & | ^ == != < <= > >= ?? ... ..<is as as?YesYesYesYes(defined as partial order in precedence groups)Yes(defined as part of precedence groups)YesYesYes
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>
YesYesYesYesYesYesYesNo
Zig() [] {} . ! ~ + +% +| - -% -| * *% *| & / % << <<| >> < <= > >= == != ^ | ++ ** .* .? = += +%= +|= -= -%= -|= *= *%= *|= /= %= &= ^= |= <<= <<|= >>=[15]and or orelse catch[15]YesYesYesYesYesYesNoNo

See also

[edit]

References

[edit]
  1. ^"Operator Input Forms—Wolfram Language Documentation".reference.wolfram.com.
  2. ^"Maxima 5.42.0 Manual: 7. Operators".maxima.sourceforge.net.
  3. ^"Prefix, Postfix and Circumfix Operators".mythryl.org.
  4. ^"Operators".doc.perl6.org.
  5. ^Pribavkina, Elena V.; Rodaro, Emanuele (2010). "State Complexity of Prefix, Suffix, Bifix and Infix Operators on Regular Languages".Developments in Language Theory. Lecture Notes in Computer Science. Vol. 6224. pp. 376–386.doi:10.1007/978-3-642-14455-4_34.ISBN 978-3-642-14454-7.
  6. ^"SWI-Prolog -- op/3".www.swi-prolog.org.
  7. ^"Defined Operations". Intel. Retrieved6 May 2025.
  8. ^"A TUTORIAL INTRODUCTION TO THE LANGUAGE B". Archived fromthe original on 2017-04-03. Retrieved2024-08-03.
  9. ^"Thompson's B Manual".www.bell-labs.com. Archived fromthe original on 2024-09-17. Retrieved2026-02-04.
  10. ^"PHP: Error Control Operators - Manual".php.net.
  11. ^"Operators".docs.perl6.org.
  12. ^"Functions".docs.perl6.org.
  13. ^ab"Operator expressions - The Rust Reference".doc.rust-lang.org. Retrieved2026-02-04.
  14. ^Goldberg, Adele; Robson, David (1983).Smalltalk-80: The Language and its Implementation(PDF). Reading, Mass.: Addison-Wesley.ISBN 0-201-11371-6.
  15. ^ab"Documentation - The Zig Programming Language".ziglang.org. Retrieved2026-02-05.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Operator_(computer_programming)&oldid=1336679709"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp