Programming Search⌘K

Conceptcore

Operator

Also called operator, operand, unary operator, binary operator, ternary operator, conditional operator, infix, prefix, postfix, arity, fixity, operator overloading, user-defined operator, compound assignment.

An operator is a symbol or a keyword, such as + or sizeof, that makes an expression from its operands. It is usually a short name for a function, with its own syntax and rules for grouping.

Applies to
core-languages

Idea

Mathematics writes 3 + 4 and not add(3, 4), and programming languages keep this short form. An operator is a symbol such as +, < or &&, or a keyword such as sizeof or typeof, that makes an expression from one or more operands. Most operators are short names for functions, and some languages let a type give its own meaning to them. Others do things that a function cannot do, such as not evaluating an operand.

import operator


class Money:
    def __init__(self, cents):
        self.cents = cents

    def __add__(self, other):  # a + b calls a.__add__(b)
        return Money(self.cents + other.cents)

    def __repr__(self):
        return f"Money({self.cents})"


# An operator is a short name for a function.
print(3 + 4, operator.add(3, 4))
print(Money(150) + Money(275))

# Arity: unary minus takes one operand, binary minus takes two.
print(-5, 10 - 5)

# Precedence and associativity decide the grouping.
print(-2 ** 2, (-2) ** 2)    # ** binds tighter than unary minus
print(2 ** 3 ** 2)           # ** groups from the right: 2 ** 9

# Some operators do not evaluate all their operands.
print(0 and 1 / 0)           # and stops at the first false operand
Output
7 7
Money(425)
-5 5
-4 4
512
0

3 + 4 and operator.add(3, 4) give the same value, because the operator is a short name for the function. Money(150) + Money(275) works because the class defines __add__. The minus sign is two operators: unary minus has one operand and binary minus has two. -2 ** 2 is -4, because ** binds tighter than the unary minus on its left, and 2 ** 3 ** 2 is 2 ** 9, because ** groups from the right. 0 and 1 / 0 gives 0 without an error, because and does not evaluate its right operand when the left one is false.

How it works

Operator and function. "An operator is a programming language construct that provides functionality that may not be possible to define as a user-defined function (e.g. sizeof in C) or has syntax different from that of a function (e.g. infix addition as in a+b)"1. In many languages, most operators map to functions. Python says that "The operator module exports a set of efficient functions corresponding to the intrinsic operators of Python. For example, operator.add(x, y) is equivalent to the expression x+y"2.

Arity and fixity. The arity of an operator is the number of its operands. "A unary operation is an operation with only one operand"3, such as -x, !x or typeof x. A binary operator has two operands, such as a + b. The conditional operator c ? a : b is ternary, and it is the only ternary operator in C, Java and JavaScript. The fixity is the position of the operator: prefix (-x), infix (a + b) or postfix (x++).

Precedence and associativity. An expression with many operators needs rules for its grouping. Precedence says which operator binds tighter, so a + b * c is a + (b * c). Associativity says how operators of the same level group, so a - b - c is (a - b) - c. In Python, "The power operator binds more tightly than unary operators on its left; it binds less tightly than unary operators on its right"4. See operator precedence.

The type of the operands. The same symbol can do different things for different types. Wikipedia gives an example: "in Java the + operator sums numbers or concatenates strings"1. The rules for numbers also differ. In Java, "Integer division rounds toward 0"5, and C, C# and Go do the same. Python // rounds toward minus infinity, so -7 // 2 is -4. Before an operation, C converts the operands to a common type, so -1 < 1u compares two unsigned values and is false. See integer representation.

Operators that are not functions. Some operators do things that a call cannot do:

  • &&, ||, and, or and ?? do not evaluate the right operand when the left one decides the result. See short-circuit evaluation.
  • In C, the operand of sizeof "is not evaluated" unless it is a variable-length array, so sizeof n++ does not change n6.
  • An assignment operator changes its left operand. In Java, "A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once"5, so b += 10 on a byte casts the result back to byte.
  • In Go, ++ and -- are statements and not expressions7, so y := x++ does not compile.

Overloading. "Some languages allow a language-defined operator to be overridden with user-defined behavior and some allow for user-defined operator symbols"1. Each language has its own mechanism:

  • Python calls a special method. "To evaluate the expression x + y, where x is an instance of a class that has an add() method, type(x).add(x, y) is called", and the reflected methods such as __radd__ handle the case where the right operand defines the operation8.
  • C++ defines functions named operator+ and similar. Some operators cannot be overloaded: "The operators :: (scope resolution), . (member access), .* (member access through pointer to member), and ?: (ternary conditional) cannot be overloaded. New operators such as **, <>, or &| cannot be created"9.
  • C# uses the operator keyword: "You can overload a predefined C# operator in a user-defined type"10.
  • Rust uses traits. "Only operators backed by traits can be overloaded. For example, the addition operator (+) can be overloaded through the Add trait"11.
  • Java and Go have no user-defined overloading. Go gives a defined type the operators of its underlying type, so Money(150) + Money(275) works for type Money int647.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the operators of JavaScript and adds type operators such as keyof, typeof and indexed access in types, but no operator overloading. No example file exists.
GoNative
RustNative
KotlinNativeKotlin maps each operator to a function by convention, so a class that declares operator fun plus supports a + b, and a in b calls contains. No example file exists because kotlinc is not installed.
SQLNativeSQL has arithmetic and comparison operators, || for string concatenation, and word operators such as LIKE, IN, BETWEEN and IS NULL, which follow the rules for NULL. No example file exists.
BashNativeBash has C-like arithmetic operators inside $(( )), and test and [[ ]] have operators such as -eq, -lt, -f and =~. No example file exists.
PowerShellNativePowerShell has named comparison operators such as -eq, -lt, -like and -match, and + joins strings and arrays. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no expressions, so it has no operators.
CSSIdiomCalc() and the other math functions use the operators +, -, * and /, and selectors use combinators such as >, + and ~.
Regular expressionsIdiomThe quantifiers *, + and ? and the alternation | act as operators on parts of a pattern, with their own precedence.
Language Verdict Mechanism
Python native special methods such as __add__; chained comparisons; operator module
JavaScript native fixed set; + converts its operands; ??, ?., typeof
TypeScript native as JavaScript; type operators such as keyof and typeof in types
Java native fixed set; + on strings; >>>; instanceof with a pattern
Kotlin native operator fun plus and similar; conventions map operators to functions
C# native operator declarations; conversion operators; ??=, ?.
Go native fixed set; no overloading; &^, <-; ++ is a statement
Rust native traits in std::ops; ?; .. and ..=
C native fixed set; sizeof; the comma operator; the usual arithmetic conversions
C++ native operator functions; <=>; function objects; user-defined literals
Bash native arithmetic in $(( )); test operators such as -eq and -f
PowerShell native -eq, -like, -match and other named operators; + on arrays and strings
SQL native arithmetic, comparison, LIKE, IN, BETWEEN, IS NULL, ||
Regex idiom quantifiers *, +, ? and alternation | act as operators on patterns
HTML n/a no expressions
CSS idiom +, -, * and / inside calc(); combinators such as > and + in selectors

Every general-purpose language has operators, so the verdict is native. The languages differ in the set of operators, in the rules for the types of the operands, and in whether a program can give operators new meanings.

The example files show these differences. Python defines +, *, the reflected __rmul__ and @ for a class, uses the operator module and shows chained comparisons, floor division and :=. JavaScript shows how + converts its operands, ?? and ||, ?., typeof and the syntax error for -2 ** 2. Java shows + on strings, integer division, >> and >>>, the cast in a compound assignment and == on objects. C# overloads +, unary -, < and a conversion to decimal. Go shows a defined type with the operators of int64, &^, <- and ++ as a statement. Rust implements Add and Neg and uses ? and ranges. C shows sizeof, the comma operator, the bitwise operators and a comparison of -1 with an unsigned value, and the compiler warns about sizeof n++ on purpose. C++ uses a defaulted <=>, an operator+, an operator<< for output, a function object and a user-defined literal.

PythonGitHub
import operator
from functools import reduce


class Vec:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __add__(self, o):
        return Vec(self.x + o.x, self.y + o.y)

    def __mul__(self, k):  # Vec * number
        return Vec(self.x * k, self.y * k)

    def __rmul__(self, k):  # number * Vec: Python tries the right operand
        return self * k

    def __matmul__(self, o):  # @ is the dot product here
        return self.x * o.x + self.y * o.y

    def __eq__(self, o):
        return (self.x, self.y) == (o.x, o.y)

    def __repr__(self):
        return f"Vec({self.x}, {self.y})"


a, b = Vec(1, 2), Vec(3, 4)
print(a + b, a * 2, 2 * a, a @ b, a == Vec(1, 2))

# The operator module gives each operator as a function.
print(reduce(operator.mul, [1, 2, 3, 4]))
print(sorted([("b", 2), ("a", 3)], key=operator.itemgetter(1)))

# Comparisons chain: 1 < x < 5 means 1 < x and x < 5.
x = 3
print(1 < x < 5, 1 < x > 5)

# // and % round toward minus infinity.
print(-7 // 2, -7 % 2)

# The walrus operator := assigns inside an expression.
if (n := len("hello")) > 3:
    print("n =", n)
Output
Vec(4, 6) Vec(2, 4) Vec(2, 4) 11 True
24
[('b', 2), ('a', 3)]
True False
-4 1
n = 5
  • Verdict: native. A class gives meaning to +, * and @ with special methods, and __rmul__ handles 2 * a, where the left operand is a number. The operator module gives each operator as a function. Comparisons chain, so 1 < x < 5 means 1 < x and x < 5. // and % round toward minus infinity. := assigns inside an expression.
#include <compare>
#include <format>
#include <iostream>
#include <string>

struct Money {
    long cents;
    // <=> with = default gives <, <=, > and >= for the type.
    auto operator<=>(const Money&) const = default;
    bool operator==(const Money&) const = default;
};

Money operator+(Money a, Money b) { return {a.cents + b.cents}; }

std::ostream& operator<<(std::ostream& os, Money m) {  // << for output is an overload
    return os << std::format("{}.{:02}", m.cents / 100, m.cents % 100);
}

// operator() makes a function object.
struct Scale {
    int k;
    int operator()(int x) const { return k * x; }
};

// A user-defined literal operator.
constexpr long operator""_usd(unsigned long long d) { return static_cast<long>(d) * 100; }

int main() {
    Money a{150}, b{275};
    std::cout << a + b << "\n";
    std::cout << (a < b) << " " << (a == b) << "\n";
    Scale triple{3};
    std::cout << triple(7) << "\n";
    std::cout << Money{12_usd} << "\n";
    std::string s = std::string("ab") + "cd";
    std::cout << s << "\n";
}
Output
4.25
1 0
21
12.00
abcd
  • Verdict: native. A defaulted <=> gives the relational operators, and a defaulted == gives equality. operator+ and operator<< are free functions. operator() makes Scale a function object. operator""_usd is a user-defined literal. + joins a std::string and a string literal.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        // + adds numbers and joins strings; Java has no other overloading of operators.
        System.out.println(1 + 2 + "x" + 1 + 2);

        // Integer / truncates toward zero, and % has the sign of the left operand.
        System.out.println((-7 / 2) + " " + (-7 % 2));

        // >> keeps the sign, and >>> shifts in zeros.
        int n = -16;
        System.out.println((n >> 2) + " " + (n >>> 28));

        // A compound assignment casts back to the type of the left side.
        byte b = 120;
        b += 10;  // b = (byte) (b + 10)
        System.out.println("b = " + b);

        // == compares references for objects; equals compares values.
        String s1 = new String("hi");
        String s2 = new String("hi");
        System.out.println((s1 == s2) + " " + s1.equals(s2));

        // instanceof with a pattern tests and binds in one operator.
        Object o = "text";
        if (o instanceof String s && s.length() > 2) {
            System.out.println("length " + s.length());
        }

        // The conditional operator ?: is the only ternary operator.
        int age = 20;
        System.out.println(age >= 18 ? "adult" : "minor");
    }
}
Output
3x12
-3 -1
-4 15
b = -126
false true
length 4
adult
  • Verdict: native. Java has a fixed set of operators, and + on a String is the only overloading. + groups from the left, so 1 + 2 is added before the strings are joined. Integer / truncates toward zero. >>> shifts in zeros. A compound assignment casts back to byte, so b wraps to -126. == compares references.
#include <stdio.h>

int main(void) {
    /* sizeof is an operator, and it does not evaluate its operand. */
    int n = 5;
    size_t s = sizeof n++;
    printf("sizeof(int) = %zu, n = %d\n", s, n);

    /* Integer / truncates toward zero, and % has the sign of the left operand. */
    printf("%d %d\n", -7 / 2, -7 % 2);

    /* The comma operator evaluates the left operand, then gives the right one. */
    int i = (n = 3, n * 2);
    printf("i = %d\n", i);

    /* Bitwise and shift operators. */
    unsigned x = 0x0F;
    printf("%u %u %u %u\n", x & 0x3, x | 0x30, x ^ 0xFF, x << 4);

    /* The conditional operator ?: is the only ternary operator. */
    printf("%s\n", n > 2 ? "big" : "small");

    /* The usual arithmetic conversions: -1 becomes a large unsigned value. */
    printf("-1 < 1u is %s\n", -1 < 1u ? "true" : "false");
    return 0;
}
Output
sizeof(int) = 4, n = 5
-3 -1
i = 6
3 63 240 240
big
-1 < 1u is false
  • Verdict: native. sizeof is an operator that does not evaluate its operand, so n stays 5, and the compiler warns about the side effect on purpose. Integer / truncates toward zero. The comma operator gives its right operand. The usual arithmetic conversions make -1 an unsigned value, so -1 < 1u is false.
var a = new Money(150);
var b = new Money(275);
Console.WriteLine(a + b);
Console.WriteLine(a < b);
Console.WriteLine(-a);

// A user-defined conversion operator.
decimal d = (decimal)b;
Console.WriteLine(d);

// ??= assigns only when the left side is null.
string? name = null;
name ??= "guest";
Console.WriteLine(name);

// is with a pattern, and the null-conditional operator ?.
object o = 42;
Console.WriteLine(o is int n and > 40 ? $"big {n}" : "other");
int[]? none = null;
Console.WriteLine(none?.Length ?? -1);

readonly record struct Money(long Cents)
{
    public static Money operator +(Money x, Money y) => new(x.Cents + y.Cents);
    public static Money operator -(Money x) => new(-x.Cents);
    public static bool operator <(Money x, Money y) => x.Cents < y.Cents;
    public static bool operator >(Money x, Money y) => x.Cents > y.Cents;
    public static explicit operator decimal(Money m) => m.Cents / 100m;
}
Output
Money { Cents = 425 }
True
Money { Cents = -150 }
2.75
guest
big 42
-1
  • Verdict: native. A type declares +, unary -, < and > with the operator keyword, and C# requires < and > as a pair. An explicit operator gives a conversion to decimal. ??= assigns only when the left side is null, and ?. gives null when the array is null.
JavaScriptGitHub
// + adds numbers and joins strings, and it converts the operands first.
console.log(1 + 2, "1" + 2, 1 + "2", [1] + [2]);

// - has no string form, so it converts strings to numbers.
console.log("5" - 2);

// ?? gives the right side only for null or undefined; || also for 0 and "".
console.log(0 ?? 7, 0 || 7);

// ?. stops at null or undefined and gives undefined.
const user = { name: "ada" };
console.log(user.address?.city);

// typeof is an operator with a name, and typeof null is "object".
console.log(typeof 42, typeof null);

// Unary minus before ** is a syntax error, so the grouping must be explicit.
try { eval("-2 ** 2"); } catch (e) { console.log(e.name); }
console.log((-2) ** 2, -(2 ** 2));

// The comma operator evaluates both operands and gives the right one.
let i = (1, 2);
console.log(i);
Output
3 12 12 12
3
0 7
undefined
number object
SyntaxError
4 -4
2
  • Verdict: native. + joins strings when one operand is a string, and it converts arrays to strings first, while - converts strings to numbers. ?? replaces only null and undefined, and || also replaces 0. ?. stops at undefined. A unary minus before ** is a syntax error. The comma operator gives its right operand.
package main

import "fmt"

type Money int64

// Go has no operator overloading, so a type uses methods.
func (m Money) Add(o Money) Money { return m + o }

func main() {
	// A defined type keeps the operators of its underlying type.
	var a, b Money = 150, 275
	fmt.Println(a+b, a.Add(b))

	// Integer / truncates toward zero, and % has the sign of the left operand.
	fmt.Println(-7/2, -7%2)

	// &^ is AND NOT: it clears the bits that are set in the right operand.
	fmt.Printf("%04b\n", 0b1111&^0b0101)

	// <- sends to a channel and receives from it.
	ch := make(chan int, 1)
	ch <- 5
	fmt.Println(<-ch)

	// & takes an address and * follows a pointer.
	x := 10
	p := &x
	*p += 1
	fmt.Println(x)

	// ++ is a statement, not an expression, so y := x++ does not compile.
	x++
	fmt.Println(x)
}
Output
425 425
-3 -1
1010
5
11
12
  • Verdict: native. Go has no operator overloading, but a defined type such as Money keeps the operators of int64. Integer / truncates toward zero. &^ clears bits. <- sends to a channel and receives from it. & and * take an address and follow a pointer. ++ is a statement, not an expression.
RustGitHub
use std::ops::{Add, Neg};

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Money(i64);

// An operator is a trait: a + b calls Add::add(a, b).
impl Add for Money {
    type Output = Money;
    fn add(self, o: Money) -> Money { Money(self.0 + o.0) }
}

impl Neg for Money {
    type Output = Money;
    fn neg(self) -> Money { Money(-self.0) }
}

fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n = s.parse::<i32>()?;  // ? returns the error early
    Ok(n * 2)
}

fn main() {
    let a = Money(150);
    let b = Money(275);
    println!("{:?} {:?} {}", a + b, -a, a < b);

    // Integer / truncates toward zero; rem_euclid gives a result that is not negative.
    println!("{} {} {}", -7 / 2, -7 % 2, (-7i32).rem_euclid(2));

    println!("{:?} {}", parse("21"), parse("x").is_err());

    // .. and ..= make ranges.
    let v: Vec<i32> = (1..=4).collect();
    println!("{:?} {:?}", v, &v[1..3]);
}
Output
Money(425) Money(-150) true
-3 -1 1
Ok(42) true
[1, 2, 3, 4] [2, 3]
  • Verdict: native. An operator is a trait in std::ops, so Money implements Add for + and Neg for unary -, and it derives PartialOrd for <. Integer / truncates toward zero, and rem_euclid gives a remainder that is not negative. ? returns an error early. .. and ..= make ranges.
  • User-defined operator symbols. Haskell, Scala, Swift and OCaml let a program define new operators from symbol characters, and Haskell and Swift let the program give them a precedence and an associativity.
  • Operators as values. In Haskell, (+) is the function behind +, and (+ 1) is a section that adds 1. Python gives the same functions in the operator module2. See higher-order functions.
  • Named operators. Some operators are words: and, or, not, is and in in Python, instanceof in Java, sizeof in C, and -eq and -like in PowerShell.
  • Chained comparisons. In Python, "x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once"4. In C and JavaScript, 1 < x < 5 compares a Boolean with 5.
  • Operators on collections. APL, NumPy and MATLAB apply an operator to each element of an array, so a + b adds two arrays element by element.

Pitfalls

  • Precedence that surprises. a & mask == 0 in C means a & (mask == 0), and -2 ** 2 in Python is -4. Use parentheses when the grouping is not obvious.
  • = and ==. if (x = 0) in C assigns and gives a false result. Java and C# reject it for an int. Many compilers warn about it.
  • == on objects. In Java, == compares references, so two equal strings made at run time can be not equal. Use equals.
  • Conversions of the operands. "5" + 2 is "52" in JavaScript, and -1 < 1u is false in C. Convert the operands explicitly.
  • Division and remainder of negative numbers. -7 / 2 is -3 and -7 % 2 is -1 in C, Java and Go, but -7 // 2 is -4 and -7 % 2 is 1 in Python.
  • Overloading that breaks the rules. An overloaded + that is not associative, or an == that does not agree with a hash, surprises the reader and breaks collections. An overloaded && in C++ evaluates both operands.

Cost

An operator on a built-in type usually compiles to one machine instruction, or to a few for division and for checks of overflow. An overloaded operator costs a function call, which the compiler can often inline in C++, C# and Rust. In Python, each operator is a call of a special method, and the interpreter also tries the reflected method when the first method returns NotImplemented.

History

The 1956 FORTRAN manual let a program write arithmetic as a formula. "The characters +, -, *, and / denote addition, subtraction, multiplication, and division", and "The symbol ** denotes exponentiation"12. It gave a "Hierarchy of Operations": exponentiation first, then multiplication and division, then addition and subtraction, and it grouped consecutive operations of one level from the left12. It did not allow A**B**C12, and later languages chose a grouping for it.

Later languages added operators for logic, bits, strings and pointers, and C gave a fixed set with many levels of precedence. C++ let a class define the meaning of most operators9, and C#, Python, Rust and Kotlin kept overloading with different mechanisms10811. Java and Go do not allow it.

References

  1. Operator (computer programming), Wikipedia, Introduction; Overloading; Customization
  2. operator, Standard operators as functions, Python documentation, Introduction
  3. Expressions and operators, MDN Web Docs, Unary operators; Binary logical operators
  4. Expressions, The Python Language Reference, 6.5 The power operator; 6.10 Comparisons
  5. The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.17.2 Division Operator /; 15.26.2 Compound Assignment Operators
  6. sizeof operator, C reference, cppreference.com, Explanation
  7. The Go Programming Language Specification, Operators; Arithmetic operators; IncDec statements
  8. Data model, The Python Language Reference, 3.3.8 Emulating numeric types
  9. Operator overloading, C++ reference, cppreference.com, Restrictions
  10. Operator overloading, C# language reference, Introduction
  11. Module std::ops, The Rust Standard Library, Module description
  12. The FORTRAN Automatic Coding System for the IBM 704 EDPM, Programmer's Reference Manual, IBM, 1956, Chapter 3, Expressions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/G225DW/text.yaml