An operator in a programming language is a symbol that tells the compiler or interpreter to perform a specific mathematical, relational or logical operation and produce a final result.
C has many powerful operators.
Many C operators are binary operators, which means they have two operands. For example, in a / b
, /
is a binary operator that accepts two operands (a
, b
).
There are some unary operators which take one operand (for example: ~
, ++
),
and only one ternary operator ? :
.
Operators have an arity, a precedence and an associativity.
Arity indicates the number of operands. In C, three different operator arities exist:
Precedence indicates which operators "bind" first to their operands. That is, which operator has priority to operate on its operands. For instance, the C language obeys the convention that multiplication and division have precedence over addition and subtraction:
a * b + c
Gives the same result as
(a * b) + c
If this is not what was wanted, precedence can be forced using parentheses, because they have the highest precedence of all operators.
a * (b + c)
This new expression will produce a result that differs from the previous two expressions.
The C language has many precedence levels; A table is given below of all operators, in descending order of precedence.
Precedence Table
Operators | Associativity |
---|---|
() [] -> . | left to right |
! ~ ++ -- + - * (dereference) (type) sizeof | right to left |
* (multiplication) / % | left to right |
+ - | left to right |
<< >> | left to right |
< <= > >= | left to right |
== != | left to right |
& | left to right |
^ | left to right |
| | left to right |
&& | left to right |
|| | left to right |
?: | right to left |
= += -= *= /= %= &= ^= |= <<= >>= | right to left |
, | left to right |
Associativity indicates how equal-precedence operators binds by default, and there are two kinds: Left-to-Right and Right-to-Left. An example of Left-to-Right binding is the subtraction operator (-
). The expression
a - b - c - d
has three identical-precedence subtractions, but gives the same result as
((a - b) - c) - d
because the left-most -
binds first to its two operands.
An example of Right-to-Left associativity are the dereference *
and post-increment ++
operators. Both have equal precedence, so if they are used in an expression such as
* ptr ++
, this is equivalent to
* (ptr ++)
because the rightmost, unary operator (++
) binds first to its single operand.