PadhaikoAll subjects

Operators and Expressions

Computer Programming (ENCT 101)

Open in the Padhaiko app

3.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:


3.2 Arithmetic, relational and logical operators

Arithmetic Operators

Arithmetic operators perform standard numerical computations on integer and floating-point operands.

C Arithmetic Operators
OperatorMeaningExample (a = 11, b = 4)ResultNotes
+Addition (or unary plus)a + b15Works on int and float/double
-Subtraction (or unary minus)a - b7Works on int and float/double
*Multiplicationa * b44Multiplication symbol is asterisk
/Divisiona / b2Truncates toward zero if both operands are integers
%Modulus (remainder)a % b3Works 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).

C Relational Operators (Example: a = 10, b = 20)
OperatorMeaningExampleResult
<Less thana < b1
<=Less than or equal toa <= 101
>Greater thana > b0
>=Greater than or equal tob >= 201
==Equal toa == b0
!=Not equal toa != b1

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.

C Logical Operators (Example: x = 5, y = 0)
OperatorNameTruth RuleExampleResult
&&Logical AND1 only if both operands are non-zerox && y0
||Logical OR1 if at least one operand is non-zerox || y1
!Logical NOTInverts truth value (0 -> 1, non-zero -> 0)!y1

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).

Assignment and Shorthand Compound Operators
OperatorExampleEquivalent ToExample (x = 10)Result
=x = 5Store 5 in xx = 55
+=x += 3x = x + 3x += 313
-=x -= 4x = x - 4x -= 46
*=x *= 2x = x * 2x *= 220
/=x /= 3x = x / 3x /= 33
%=x %= 4x = x % 4x %= 42

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).

AspectPrefix (++x / --x)Postfix (x++ / x--)
Order of ActionIncrements/decrements x first, then returns the new valueReturns the original value of x first, then increments/decrements x
Trace (int x = 5, y;)y = ++x; -> x = 6, y = 6y = x++; -> y = 5, x = 6
MnemonicChange then useUse 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).

C Bitwise Operators (8-bit example: a = 12 = 00001100, b = 10 = 00001010)
OperatorNameBit-by-Bit RuleResult (Binary)Result (Decimal)
&Bitwise AND1 only if both bits are 1000010008
|Bitwise OR1 if either bit is 10000111014
^Bitwise XOR1 if bits are different000001106
~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)0011000048
>>Right Shift (a >> 2)Shifts bits right by 2 (divides unsigned by 2^2 = 4)000000113
AspectLogical (&&, ||, !)Bitwise (&, |, ~)
Level of OperationOperates on whole truth values (0 = false, non-zero = true)Operates independently on every bit position of integer operands
Output ValueAlways 0 or 1An integer formed from the resulting bit pattern
Example (5 and 2)5 && 2 -> 1 (both non-zero)5 & 2 (0101 & 0010) -> 0 (0000)
Short-CircuitingYes (&& and || short-circuit)No (both operands always evaluated)

Special Operators


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.

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:


3.6 Evaluation and type conversion in expressions

When evaluating a mixed-type expression in C, the compiler follows Usual Arithmetic Conversions:

  1. Integer Promotion: Any char or short operand is automatically promoted to int (or unsigned int) before arithmetic.
  2. 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.
  3. 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 double to int).

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).

C Operator Precedence and Associativity (Highest to Lowest)
Precedence LevelOperator(s)DescriptionAssociativity
1 (Highest)(), [], ., ->, postfix ++, --Grouping, array subscript, member access, postfix inc/decL -> R
2unary +, -, !, ~, prefix ++, --, (type), *, &, sizeofUnary operators, casts, dereference, address-of, sizeR -> L
3*, /, %MultiplicativeL -> R
4+, -AdditiveL -> R
5<<, >>Bitwise shiftL -> R
6<, <=, >, >=Relational comparisonL -> R
7==, !=Equality comparisonL -> R
8&Bitwise ANDL -> R
9^Bitwise XORL -> R
10|Bitwise ORL -> R
11&&Logical ANDL -> R
12||Logical ORL -> R
13?:Ternary conditionalR -> L
14=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=Assignment and compound assignmentR -> L
15 (Lowest),Comma operatorL -> R

Worked Examples

Example 1

1 (6 marks)

Evaluate the following C expressions step by step using operator precedence and associativity rules, assuming int a = 10, b = 5, c = 3, d = 4;:

  1. a + 2 * b / c - d % c
  2. b > 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:
    1. 2 * 5 = 10
    2. 10 / 3 = 3 (integer division truncates 3.33 to 3)
    3. 4 % 3 = 1 (remainder of 4 / 3)
  • Expression reduces to 10 + 3 - 1.
  • Additive operators (+, -) share level 4 precedence and associate left-to-right:
    1. 10 + 3 = 13
    2. 13 - 1 = 12.

Evaluating Expression 2: b > c && 2 != 2 || !0:

  1. Unary !0 evaluates to 1.
  2. Relational 5 > 3 evaluates to 1.
  3. Equality 2 != 2 evaluates to 0.
  4. Logical AND 1 && 0 evaluates to 0.
  5. Logical OR 0 || 1 evaluates to 1.
Answer:
  1. a + 2 * b / c - d % c = 12
  2. b > c && 2 != 2 || !0 = 1
Example 2

2 (6 marks)

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 = 00101101
  • 27 = 16 + 8 + 2 + 1 = 00011011

Applying Bitwise Operations Bit by Bit:

Bitwise Operation Results on 45 and 27
OperationBinary Calculation8-Bit ResultDecimal Result
x & y00101101 & 00011011000010019
x | y00101101 | 000110110011111163
x ^ y00101101 ^ 000110110011011054
y << 2Shift 00011011 left 2 bits01101100108 (27 * 4)
x >> 2Shift 00101101 right 2 bits0000101111 (45 / 4)
Answer:
  • x & y = 9 (00001001)
  • x | y = 63 (00111111)
  • x ^ y = 54 (00110110)
  • y << 2 = 108 (01101100)
  • x >> 2 = 11 (00001011)
Example 3

3 (6 marks)

Trace the output of the following C program involving prefix/postfix operators, short-circuit logical evaluation, sizeof, and the comma operator:

Operator Side Effects and Precedence TraceC
#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);:

  • a is 5, so a > 10 is 0 (false).
  • Because of short-circuit evaluation in &&, the right-hand operand (++b > 5) is skipped completely.
  • Thus flag becomes 0, and b remains 10.

Tracing res = (a++, b += 2, a + b);:

  • The comma operator evaluates left-to-right:
    1. a++ increments a from 5 to 6.
    2. b += 2 updates b from 10 to 12.
    3. a + b evaluates to 6 + 12 = 18, which becomes the value of the comma expression assigned to res.

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.

Answer:

Output (assuming 4-byte int):

Program OutputText
a=6 b=12 flag=0 res=18 sz=4
final_a=6

Exercises

Exercises — Operators and Expressions

Question 1

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:

  1. 17 % 5 = 2 (remainder of 17 divided by 5)
  2. 4 * 2 = 8
  3. 17 / 4 = 4 (integer division truncates 4.25 to 4)

Additive Pass (Left-to-Right): The expression reduces to 2 + 8 - 4:

  1. 2 + 8 = 10
  2. 10 - 4 = 6
Answer:

6 (since 17 % 5 = 2, 4 * 2 = 8, 17 / 4 = 4, and 2 + 8 - 4 = 6).

Question 2

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 return 0 or 1, 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 && 2 evaluates to 1 (both operands are non-zero).
  • 4 & 2 computes 0100 & 0010 = 0000, which equals 0.
Answer:

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.

Question 3

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;: increments x first to 15, then assigns 15 to y (x = 15, y = 15).
  • y = x++;: assigns current x (14) to y first, then increments x to 15 (x = 15, y = 14).
Answer:

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.

Question 4

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 = 4
  • 22 | 13 = 00010110 | 00001101 = 00011111 = 31
  • 22 ^ 13 = 00010110 ^ 00001101 = 00011011 = 27
  • 13 << 3 = shift 00001101 left 3 bits = 01101000 = 104 (13 * 8)
Answer:

22 & 13 = 4, 22 | 13 = 31, 22 ^ 13 = 27, and 13 << 3 = 104.

Question 5

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);:

  1. k += 2 executes first, changing k from 3 to 5.
  2. k * 4 evaluates next as 5 * 4 = 20.
  3. The comma operator returns the rightmost result, so m = 20 (and k = 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.

Answer:

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).

← Overview of C ProgrammingInput and Output →