Operators
Many programming languages implement the same operators for common operations, with some considerations:
- β οΈ The symbol may be different
- π₯ The logic may be different
- π‘ There may be a function instead of an operator
The most common operator is the assignment operator, which is usually =
. It's used to store a value in a container called a variable.
x = 5
β οΈ Some languages use :=
or <-
.
Arithmetic operators
These operators represent arithmetic operations.
- x plus 1 β
x + 1
- x minus 1 β
x - 1
- x by 1 β
x * 1
- x divided by 1 β
x / 1
π₯ Languages can handle numbers differently. If you try 5 / 2
, some languages will return 2.5
while others may return 2
.
π₯ Some languages may have implemented additional operators:
- Exponentiation ($x^n$) is often
x ** n
orx ^ n
- Modulus ($a\mod b$) is often
a % b
When we are updating the variable of a variable, such as x = x + 1
, some languages implemented shortcuts :
x += 1 // same as "x = x + 1"
x -= 1 // same as "x = x - 1"
x *= 1 // same as "x = x * 1"
x /= 1 // same as "x = x / 1"
π₯ Some languages have a shortcut when the operand is 1
, which is common in loops: x++
(x = x + 1) and x--
(x = x - 1).
π₯ Some languages may also implement ++x
, and --x
. When using this variant, the operation has a higher priority than any other.
-
if (x++ == 1)
: we havex == 1
thenx = x + 1
-
if (++x == 1)
: we havex = x + 1
thenx == 1
Comparison operators
Most of the time, we are executing a different code according to the value of a variable. We have operators to compare variables/values.
- x is greater than 1 β
x > 1
- x is greater than or equal to 1 β
x >= 1
- x is less than or equal to 1 β
x <= 1
- x is less than 1 β
x < 1
- x is equal to 1 β
x == 1
- x is not equal to 1 β
x != 1
orx <> 1
(β οΈ)
π₯ Languages may implement strict comparison. Strict comparison will also check the type of the variable (ex: 5.0 === 5 is false).
π₯ Languages may have more implementation-specific operators. For instance, many languages have an operator in
to check if a variable is part of another variable (ex: character in a string, value in an array...).
As we may chain multiple comparisons, we also have logical operators:
-
a && b
: true if botha
andb
are true -
a || b
: true if at least one is true -
!a
: negate the result (false β true, true β false)
β οΈ Some languages use and
/or
/not
instead of &&
/||
/!
.
π₯ Most languages have implemented Short-circuit_evaluation. If we write true || anythingElse
, then the rest of the condition is not evaluated, as we already know the result is true
.