Operators and Expressions
Open in the Padhaiko app3.1 Introduction to operators and expressions
An operator is a symbol that instructs the C compiler to perform a specific mathematical, relational, logical, or bitwise manipulation on one or more values. The data items on which an operator acts are called operands, and a valid combination of operators, operands, constants, and function calls that yields a value is an expression.
C classifies operators by the number of operands they require:
- Unary operators: Act on a single operand (e.g.,
-x,++i,!flag,&var,sizeof(int)). - Binary operators: Act on two operands (e.g.,
a + b,x == y,p && q). - Ternary operator: Acts on three operands (
condition ? expr1 : expr2).
3.2 Arithmetic, relational and logical operators
Arithmetic Operators
Arithmetic operators perform standard numerical computations on integer and floating-point operands.
| Operator | Meaning | Example (a = 11, b = 4) | Result | Notes |
|---|---|---|---|---|
+ | Addition (or unary plus) | a + b | 15 | Works on int and float/double |
- | Subtraction (or unary minus) | a - b | 7 | Works on int and float/double |
* | Multiplication | a * b | 44 | Multiplication symbol is asterisk |
/ | Division | a / b | 2 | Truncates toward zero if both operands are integers |
% | Modulus (remainder) | a % b | 3 | Works only on integer types (int, char, long); invalid on float/double |
Relational Operators
Relational operators compare two values and yield an integer Boolean result: 1 (true) or 0 (false).
| Operator | Meaning | Example | Result |
|---|---|---|---|
< | Less than | a < b | 1 |
<= | Less than or equal to | a <= 10 | 1 |
> | Greater than | a > b | 0 |
>= | Greater than or equal to | b >= 20 | 1 |
== | Equal to | a == b | 0 |
!= | Not equal to | a != b | 1 |
Logical Operators
Logical operators combine or negate truth conditions. In C, zero (0) is false and any non-zero value is true. Logical operators always evaluate to 1 or 0.
| Operator | Name | Truth Rule | Example | Result |
|---|---|---|---|---|
&& | Logical AND | 1 only if both operands are non-zero | x && y | 0 |
|| | Logical OR | 1 if at least one operand is non-zero | x || y | 1 |
! | Logical NOT | Inverts truth value (0 -> 1, non-zero -> 0) | !y | 1 |
3.3 Assignment, increment and decrement operators
Assignment and Compound Assignment Operators
The simple assignment operator = evaluates the right-hand side and stores the value in the left-hand variable (which must be a modifiable lvalue).
| Operator | Example | Equivalent To | Example (x = 10) | Result |
|---|---|---|---|---|
= | x = 5 | Store 5 in x | x = 5 | 5 |
+= | x += 3 | x = x + 3 | x += 3 | 13 |
-= | x -= 4 | x = x - 4 | x -= 4 | 6 |
*= | x *= 2 | x = x * 2 | x *= 2 | 20 |
/= | x /= 3 | x = x / 3 | x /= 3 | 3 |
%= | x %= 4 | x = x % 4 | x %= 4 | 2 |
Increment (++) and Decrement (--) Operators
++ adds 1 to a variable and -- subtracts 1. Each has a prefix form (before the variable) and a postfix form (after the variable).
| Aspect | Prefix (++x / --x) | Postfix (x++ / x--) |
|---|---|---|
| Order of Action | Increments/decrements x first, then returns the new value | Returns the original value of x first, then increments/decrements x |
Trace (int x = 5, y;) | y = ++x; -> x = 6, y = 6 | y = x++; -> y = 5, x = 6 |
| Mnemonic | Change then use | Use then change |
3.4 Conditional, bitwise and special operators
Conditional (Ternary) Operator (?:)
The conditional operator is C's only ternary operator: condition ? expr_if_true : expr_if_false
If condition is non-zero, expr_if_true is evaluated and returned; otherwise expr_if_false is evaluated and returned. Example: max = (a > b) ? a : b;
Bitwise Operators
Bitwise operators manipulate individual binary bits of integer operands (char, short, int, long, unsigned).
| Operator | Name | Bit-by-Bit Rule | Result (Binary) | Result (Decimal) |
|---|---|---|---|---|
& | Bitwise AND | 1 only if both bits are 1 | 00001000 | 8 |
| | Bitwise OR | 1 if either bit is 1 | 00001110 | 14 |
^ | Bitwise XOR | 1 if bits are different | 00000110 | 6 |
~ | Bitwise NOT (1's complement) | Flips every bit (0 <-> 1) | 11110011 (unsigned 8-bit) | 243 (-13 in signed) |
<< | Left Shift (a << 2) | Shifts bits left by 2, fills right with 0 (multiplies by 2^2 = 4) | 00110000 | 48 |
>> | Right Shift (a >> 2) | Shifts bits right by 2 (divides unsigned by 2^2 = 4) | 00000011 | 3 |
| Aspect | Logical (&&, ||, !) | Bitwise (&, |, ~) |
|---|---|---|
| Level of Operation | Operates on whole truth values (0 = false, non-zero = true) | Operates independently on every bit position of integer operands |
| Output Value | Always 0 or 1 | An integer formed from the resulting bit pattern |
Example (5 and 2) | 5 && 2 -> 1 (both non-zero) | 5 & 2 (0101 & 0010) -> 0 (0000) |
| Short-Circuiting | Yes (&& and || short-circuit) | No (both operands always evaluated) |
Special Operators
- Address-of (
&) and Dereference (*):&xyields the memory address ofx;*ptraccesses the value stored at pointerptr. - Member selection (
.and->): Access fields of structures and unions. - Type cast
(type): Explicitly converts an expression to the named type.
3.5 Comma operator, size of operator
The Comma Operator (,)
The comma operator links two or more expressions sequentially from left to right. Every sub-expression is evaluated for its side effects, and the entire comma expression evaluates to the value and type of the rightmost expression.
- Example:
int x = (a = 3, b = 4, a + b);setsa = 3,b = 4, and assigns7tox. - Note that commas separating function arguments (
printf("%d %d", a, b);) or variable declarations (int a = 1, b = 2;) act as separators, not the comma operator.
The sizeof Operator
sizeof is a compile-time unary operator (not a function) that returns the size in bytes (as size_t) occupied by a data type or variable:
sizeof(type)(parentheses required for a type name, e.g.,sizeof(double)->8).sizeof expr(parentheses optional for a variable/expression, e.g.,sizeof x).- Important exam trap:
sizeofdoes not evaluate side effects inside its operand! For example,sizeof(i++)returnssizeof(int)(4) and leavesiunchanged.
3.6 Evaluation and type conversion in expressions
When evaluating a mixed-type expression in C, the compiler follows Usual Arithmetic Conversions:
- Integer Promotion: Any
charorshortoperand is automatically promoted toint(orunsigned int) before arithmetic. - Binary Balancing: If the two operands still have different types, the operand of lower rank is converted to the type of the higher-rank operand along the hierarchy:
int -> unsigned int -> long -> unsigned long -> long long -> float -> double -> long double. - Assignment Conversion: After the right-hand side is completely evaluated, the result is converted to the type of the left-hand variable (which may truncate decimals if assigning
doubletoint).
3.7 Operator precedence and associativity
Precedence determines which operator binds first when multiple operators appear in one expression without parentheses. Associativity resolves tie-breaking when two operators share the same precedence level (either Left-to-Right L -> R or Right-to-Left R -> L).
| Precedence Level | Operator(s) | Description | Associativity |
|---|---|---|---|
| 1 (Highest) | (), [], ., ->, postfix ++, -- | Grouping, array subscript, member access, postfix inc/dec | L -> R |
| 2 | unary +, -, !, ~, prefix ++, --, (type), *, &, sizeof | Unary operators, casts, dereference, address-of, size | R -> L |
| 3 | *, /, % | Multiplicative | L -> R |
| 4 | +, - | Additive | L -> R |
| 5 | <<, >> | Bitwise shift | L -> R |
| 6 | <, <=, >, >= | Relational comparison | L -> R |
| 7 | ==, != | Equality comparison | L -> R |
| 8 | & | Bitwise AND | L -> R |
| 9 | ^ | Bitwise XOR | L -> R |
| 10 | | | Bitwise OR | L -> R |
| 11 | && | Logical AND | L -> R |
| 12 | || | Logical OR | L -> R |
| 13 | ?: | Ternary conditional | R -> L |
| 14 | =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>= | Assignment and compound assignment | R -> L |
| 15 (Lowest) | , | Comma operator | L -> R |
Worked Examples
1
Evaluate the following C expressions step by step using operator precedence and associativity rules, assuming int a = 10, b = 5, c = 3, d = 4;:
a + 2 * b / c - d % cb > c && 2 != 2 || !0
Evaluating Expression 1: a + 2 * b / c - d % c: Substitute values: 10 + 2 * 5 / 3 - 4 % 3.
- Multiplicative operators (
*,/,%) share level 3 precedence and associate left-to-right:2 * 5=1010 / 3=3(integer division truncates3.33to3)4 % 3=1(remainder of4 / 3)
- Expression reduces to
10 + 3 - 1. - Additive operators (
+,-) share level 4 precedence and associate left-to-right:10 + 3=1313 - 1=12.
Evaluating Expression 2: b > c && 2 != 2 || !0:
- Unary
!0evaluates to1. - Relational
5 > 3evaluates to1. - Equality
2 != 2evaluates to0. - Logical AND
1 && 0evaluates to0. - Logical OR
0 || 1evaluates to1.
a + 2 * b / c - d % c= 12b > c && 2 != 2 || !0= 1
2
Given unsigned char x = 45, y = 27;, compute x & y, x | y, x ^ y, y << 2, and x >> 2 in both 8-bit binary and decimal.
Converting 45 and 27 to 8-Bit Binary:
45 = 32 + 8 + 4 + 1=0010110127 = 16 + 8 + 2 + 1=00011011
Applying Bitwise Operations Bit by Bit:
| Operation | Binary Calculation | 8-Bit Result | Decimal Result |
|---|---|---|---|
x & y | 00101101 & 00011011 | 00001001 | 9 |
x | y | 00101101 | 00011011 | 00111111 | 63 |
x ^ y | 00101101 ^ 00011011 | 00110110 | 54 |
y << 2 | Shift 00011011 left 2 bits | 01101100 | 108 (27 * 4) |
x >> 2 | Shift 00101101 right 2 bits | 00001011 | 11 (45 / 4) |
x & y= 9 (00001001)x | y= 63 (00111111)x ^ y= 54 (00110110)y << 2= 108 (01101100)x >> 2= 11 (00001011)
3
Trace the output of the following C program involving prefix/postfix operators, short-circuit logical evaluation, sizeof, and the comma operator:
#include <stdio.h>
int main(void) {
int a = 5, b = 10, res;
int flag = (a > 10) && (++b > 5);
res = (a++, b += 2, a + b);
printf("a=%d b=%d flag=%d res=%d sz=%zu\n", a, b, flag, res, sizeof(a++));
printf("final_a=%d\n", a);
return 0;
}Tracing flag = (a > 10) && (++b > 5);:
ais5, soa > 10is0(false).- Because of short-circuit evaluation in
&&, the right-hand operand(++b > 5)is skipped completely. - Thus
flagbecomes0, andbremains10.
Tracing res = (a++, b += 2, a + b);:
- The comma operator evaluates left-to-right:
a++incrementsafrom5to6.b += 2updatesbfrom10to12.a + bevaluates to6 + 12 = 18, which becomes the value of the comma expression assigned tores.
Tracing sizeof(a++): sizeof is evaluated at compile time using the type of a++ (int), which is 4 bytes on typical 32/64-bit systems. The expression a++ is not executed, so a stays 6.
Output (assuming 4-byte int):
a=6 b=12 flag=0 res=18 sz=4
final_a=6Exercises
Exercises — Operators and Expressions
Evaluate 17 % 5 + 4 * 2 - 17 / 4 in C, clearly showing the precedence and associativity of each operator used.
Step-by-step Precedence Evaluation: All three multiplicative operators (%, *, /) share higher precedence than + and -, and evaluate left-to-right:
17 % 5=2(remainder of 17 divided by 5)4 * 2=817 / 4=4(integer division truncates4.25to4)
Additive Pass (Left-to-Right): The expression reduces to 2 + 8 - 4:
2 + 8=1010 - 4=6
6 (since 17 % 5 = 2, 4 * 2 = 8, 17 / 4 = 4, and 2 + 8 - 4 = 6).
Differentiate between logical operators (&&, ||, !) and bitwise operators (&, |, ~) with a concrete numerical example showing where && and & produce different results.
Key Differences:
- Logical operators treat operands as whole Boolean values (
0= false, non-zero = true), always return0or1, and support short-circuiting (&&,||). - Bitwise operators act independently on each binary bit of integer operands, return a full bit-pattern integer, and always evaluate both operands.
Concrete Counterexample (a = 4, b = 2): In binary, 4 = 0100 and 2 = 0010:
4 && 2evaluates to1(both operands are non-zero).4 & 2computes0100 & 0010 = 0000, which equals0.
Logical operators test whole-value truthiness (0 vs non-zero) and yield 0 or 1 with short-circuiting, whereas bitwise operators operate bit-by-bit on integers. For example, 4 && 2 gives 1, while 4 & 2 gives 0.
Explain the ternary conditional operator (?:) with syntax and write a single C statement using ?: to find the largest of three integers a, b, and c. Also distinguish y = ++x; from y = x++; when x = 14.
Ternary Conditional Operator: Syntax: condition ? expr1 : expr2. It evaluates condition; if true (non-zero), the result is expr1, otherwise expr2. To find the largest of three integers a, b, and c: max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
Prefix vs. Postfix Increment (x = 14):
y = ++x;: incrementsxfirst to15, then assigns15toy(x = 15, y = 15).y = x++;: assigns currentx(14) toyfirst, then incrementsxto15(x = 15, y = 14).
Nested ternary for maximum of three numbers: max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);. For x = 14, y = ++x yields x = 15, y = 15, whereas y = x++ yields x = 15, y = 14.
Using 8-bit binary arithmetic, evaluate 22 & 13, 22 | 13, 22 ^ 13, and 13 << 3.
Binary Representation:
22=00010110(16 + 4 + 2)13=00001101(8 + 4 + 1)
Bitwise Calculations:
22 & 13=00010110 & 00001101=00000100=422 | 13=00010110 | 00001101=00011111=3122 ^ 13=00010110 ^ 00001101=00011011=2713 << 3= shift00001101left 3 bits =01101000=104(13 * 8)
22 & 13 = 4, 22 | 13 = 31, 22 ^ 13 = 27, and 13 << 3 = 104.
What are the uses and return values of the comma operator (,) and the sizeof operator in C? Trace int k = 3; int m = (k += 2, k * 4); and int s = sizeof(k++);.
Comma Operator Trace: In m = (k += 2, k * 4);:
k += 2executes first, changingkfrom3to5.k * 4evaluates next as5 * 4 = 20.- The comma operator returns the rightmost result, so
m = 20(andk = 5).
sizeof Operator Trace: In s = sizeof(k++);, sizeof determines the byte size of k's type (int, typically 4 bytes) at compile time without evaluating k++. Therefore s = 4 (on a 32-bit int system) and k remains 5.
The comma operator evaluates sub-expressions left-to-right and yields the rightmost value (m = 20, k = 5). The sizeof operator returns the byte size at compile time without executing operand side effects (s = sizeof(int), typically 4, while k stays 5).