Arithmetic Operators and Operator Precedence
Arithmetic Operators and Operator Precedence
Introduction
In the C programming language, operators are symbols that perform specific operations on one or more operands. Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, and modulus. Operator precedence defines the order in which these operators are evaluated in an expression, ensuring correct results when multiple operators are present. Understanding operator precedence is critical for writing accurate and efficient C code.
Arithmetic Operators
C supports the following arithmetic operators:
+– Addition-– Subtraction*– Multiplication/– Division%– Modulus (remainder of division)
These operators are applied to operands in the order they appear in the expression. For example:
int result = 5 + 3 * 2;
// result is 11 (due to operator precedence)
Operator Precedence
Operator precedence determines the hierarchy of operations in an expression. Operators with higher precedence are evaluated before those with lower precedence. The precedence levels, from highest to lowest, are:
- Parentheses (
()) - Multiplication (
*,/) - Addition (
+,-) - Modulus (
%) - Shift (
<<,>>)
For example:
int a = 10 - 3 * 2 + 4 / 2;
// precedence evaluates multiplication and division first:
// 3 * 2 = 6, 4 / 2 = 2 → a = 10 - 6 + 2 = 6
Operator Precedence Examples
Expressions with mixed operators require careful evaluation of precedence to avoid incorrect results. Consider the following:
3 + 4 * 2- Multiplication (
*) has higher precedence than addition (+). - Result:
3 + (4 * 2) = 3 + 8 = 11
- Multiplication (
10 - 3 * 2 + 4 / 2- Multiplication and division are evaluated first.
- Result:
10 - (3 * 2) + (4 / 2) = 10 - 6 + 2 = 6
(3 + 4) * 2- Parentheses override precedence.
- Result:
(7) * 2 = 14
Order of Evaluation
Operators with the same precedence are evaluated from left to right. For instance:
int a = 10 - 3 + 2;
// evaluated left to right: 10 - 3 = 7, then 7 + 2 = 9
Practical Implications
Understanding operator precedence is essential for writing correct expressions. For example:
5 + 3 * 2→11(multiplication first)5 - 3 + 2→4(left to right evaluation)5 / 2→2(integer division in C)
Conclusion
Arithmetic operators in C are fundamental to constructing valid expressions. Operator precedence ensures that operations are performed in the correct order, preventing errors in calculations. By adhering to the precedence hierarchy and understanding the order of evaluation, developers can write efficient and reliable C code.