First Year Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Operators and expressions

Operators, expressions, precedence, associativity, conversions, and side effects in C, with syntax, rules, examples, pitfalls, and exam pointers.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Engineers use operators and expressions in C to compute values, make decisions, access memory, and control hardware bits. Clear understanding prevents logical errors, undefined behavior, and bugs that are hard to trace.

Key ideas

  • Expression: A combination of operands and operators that the compiler evaluates to a value (and possibly a side effect). Example: a + b * 3.
  • Precedence: The rule that decides which operator is evaluated first when operators are mixed in one expression (e.g., * before +).
  • Associativity: The rule that decides the evaluation order when operators of the same precedence appear (e.g., left-to-right for +, right-to-left for =). Associativity is about how expressions are grouped syntactically, not necessarily the order of actual evaluation of subexpressions.
  • Value category: In C, an lvalue designates an object that occupies identifiable storage (you can take its address with &), e.g., x, arr[0]. An rvalue is a temporary value not associated with a specific storage location, e.g., x + 1. Some expressions are lvalues but not modifiable (e.g., string literal), and some operators yield lvalues (e.g., *p, arr[i]).
  • Side effect: A change in program state during evaluation (e.g., modifying a variable using ++, assignment, I/O). Example: in x = y++, x receives old y, and y increases by 1 as a side effect.
  • Sequence/short-circuit rules: Logical && and || operators evaluate left operand first and evaluate the right operand only if needed (short-circuit). The conditional ?: first evaluates the condition, then exactly one of the second or third operands. These rules control when side effects occur. Except for these, the comma operator, and the end of a full expression (such as before a semicolon), C does not specify the order of evaluation of operands or function-call arguments; do not rely on left-to-right evaluation.
  • Undefined behavior (UB): Program behavior that the C standard does not define; any result can happen. A classic case is modifying a scalar multiple times between sequence points without an intervening sequence rule that orders them. Example (do not write): i = i++ + ++i; is undefined.
  • Integer promotions: Before most arithmetic operations on types smaller than int (e.g., char, short), values are converted to int (or unsigned int) as per implementation rules.
  • Usual arithmetic conversions: When binary arithmetic operators act on different arithmetic types, the operands are converted to a common type to perform the operation (e.g., int + double converts to double).
  • Implicit conversions (type coercions): Automatic type changes applied by the compiler in expressions, assignments, and function calls. May cause loss of information (e.g., assigning double to int truncates the fraction).
  • Overflow and implementation-defined behavior: Signed integer overflow is undefined behavior; unsigned integer arithmetic wraps modulo 2^n. Right shift of a negative signed integer is implementation-defined (arithmetic vs logical shift may differ by implementation).
  • Bitwise vs logical operators: Bitwise (&, |, ^, ~, <<, >>) act on individual bits. Logical (&&, ||, !) treat any nonzero as true and zero as false, and yield 0 or 1. Relational operators (<, <=, >, >=, ==, !=) also yield 0 or 1 of type int.
  • Assignment operators: =, and compound assignments like +=, -=, etc. The left operand must be a modifiable lvalue.
  • Increment/decrement: ++x (pre-increment) increases x then yields the new value; x++ (post-increment) yields the old value then increases x. Both require a modifiable lvalue operand.
  • Pointer operators: &x (address of), *p (indirection to obtain the object pointed to by p), p[i] (equivalent to *(p + i)), and -> (member access through pointer; p->m is (*p).m).
  • Conditional operator: cond ? expr1 : expr2 evaluates to expr1 if cond is true, else expr2. Only one of expr1/expr2 is evaluated.
  • Cast: (type)expression converts a value to a specified type explicitly. Use with care because information can be lost.
  • sizeof operator: sizeof (type-or-expression) yields the size in bytes (of type size_t) of the given type or the operand’s type. It does not evaluate its expression operand, except when the operand is of variable length array (VLA) type, in which case the size expressions are evaluated at run time.

Exact statements you can write in an exam:

  • Definition (Operator): “An operator in C is a symbol which instructs the compiler to perform a specific mathematical, logical, or bit-level operation on its operands.”
  • Definition (Expression): “An expression in C is a valid combination of constants, variables, operators, and function calls that the compiler evaluates to a single value and may produce side effects.”
  • Law (Precedence): “In C, the precedence of operators determines the grouping of operands in the absence of parentheses; higher-precedence operators bind more tightly.” Assumption: Standard C precedence rules apply.
  • Law (Associativity): “If two operators of the same precedence compete for the same operands, associativity decides their grouping: most binary operators are left-to-right associative; assignment and conditional operators are right-to-left.”
  • Rule (Short-circuit): “For E1 && E2, E1 is evaluated first; if E1 is false, E2 is not evaluated. For E1 || E2, E1 is evaluated first; if E1 is true, E2 is not evaluated.”
  • Rule (Integer promotions): “Operands of type char and short are converted to int (or unsigned int if int cannot represent all values) before arithmetic.”
  • Rule (Usual arithmetic conversions): “If the operands of a binary arithmetic operator have different types, they are converted to a common real type: if either is long double, both to long double; else if either double, both to double; else if either float, both to float; otherwise perform integer promotions and then balance signed/unsigned ranks.”
  • Rule (Assignment): “In E1 op= E2, the right operand E2 is converted to the type of E1 as in simple assignment, then the operation is performed.”

What to draw if asked for a diagram of precedence and associativity:

  • Draw a vertical list (a ladder) of operator groups, highest precedence at the top. Label each rung with the operators and their associativity arrows: e.g., top rung: () [] -> . (left-to-right), next: ! ~ ++ -- + - (cast) * & sizeof (right-to-left), then * / % (left-to-right), then + -, then << >>, then < <= > >=, then == !=, then &, then ^, then |, then &&, then ||, then ?: (right-to-left), then assignments (right-to-left), bottom , (left-to-right). Add a key: “Higher is tighter binding.”

Notes on data sizes and portability:

  • The exact sizes of integer types (int, long, etc.) and behavior of right shift on negative signed integers are implementation-defined. Do not assume specific byte sizes or shift behavior in exams unless asked to state for a particular compiler/platform.

Formulas

For a programming topic, use syntax and key operator forms:

  • Parentheses/grouping: ( expression )
  • Array subscript: expr[expr]
  • Structure/union member: expr.member and ptr->member
  • Function call: func(arg1, arg2, ...)
  • Postfix increment/decrement: expr++, expr--
  • Prefix unary: ++expr, --expr, +expr, -expr, !expr, ~expr
  • Address and indirection: &expr, *expr
  • Cast: (type) expression
  • Sizeof: sizeof (type) or sizeof expression
  • Multiplicative: expr * expr, expr / expr, expr % expr
  • Additive: expr + expr, expr - expr
  • Shifts: expr << expr, expr >> expr
  • Relational: expr < expr, expr <= expr, expr > expr, expr >= expr
  • Equality: expr == expr, expr != expr
  • Bitwise: expr & expr, expr ^ expr, expr | expr, ~expr
  • Logical: expr && expr, expr || expr, !expr
  • Conditional: cond ? expr1 : expr2
  • Assignment: lhs = rhs, lhs op= rhs where op is + - * / % << >> & ^ |
  • Comma: expr1 , expr2

Operator precedence and associativity (high to low; same line = same precedence):

  • () [] -> . ++ -- (postfix) (left-to-right)
  • ++ -- + - ! ~ * & (type) sizeof (unary) (right-to-left)
  • * / % (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)

Worked examples

Example 1: Precedence, associativity, and implicit conversions

Code:

#include <stdio.h>

int main(void) {
    int a = 5, b = 2, c = 3;

    /* Mixed operators with precedence and an explicit cast */
    double r = a + b * c - 4 / b + (double)a / b;

    /* Demonstrate pre vs post increment safely (in separate statements) */
    int p = 3; 
    int q = p++; // q = 3, p becomes 4
    int r2 = 3; 
    int s = ++r2; // r2 becomes 4, s = 4

    printf("r = %.1f\n", r);
    printf("After q = p++ starting from p=3: q=%d, p=%d\n", q, p);
    printf("After s = ++r2 starting from r2=3: s=%d, r2=%d\n", s, r2);
    
    /* Associativity (left-to-right) for subtraction */
    int t = 10 - 3 - 2; // (10 - 3) - 2 = 5
    printf("t = %d\n", t);

    return 0;
}

Sample input:

  • (no input)

Exact output:

r = 11.5
After q = p++ starting from p=3: q=3, p=4
After s = ++r2 starting from r2=3: s=4, r2=4
t = 5

Why: * and / bind before +/-; integer division 4/b is 2; (double)a/b forces floating division; subtraction associates left-to-right.

Example 2: Bitwise set, clear, toggle, and test

Code:

#include <stdio.h>
#include <stdbool.h>

/* k is the bit index from 0 (LSB). */
static unsigned int set_bit(unsigned int n, unsigned int k)   { return n | (1u << k); }
static unsigned int clear_bit(unsigned int n, unsigned int k) { return n & ~(1u << k); }
static unsigned int toggle_bit(unsigned int n, unsigned int k){ return n ^ (1u << k); }
static bool check_bit(unsigned int n, unsigned int k)         { return (n >> k) & 1u; }

int main(void) {
    unsigned int n = 0x29u; // 41 decimal, binary 0010 1001
    unsigned int k = 3;     // choose the 3rd bit (LSB is bit 0)

    unsigned int a = set_bit(n, k);
    unsigned int b = clear_bit(n, k);
    unsigned int c = toggle_bit(n, k);
    bool present = check_bit(n, k);

    printf("n = %u (0x%X)\n", n, n);
    printf("After set_bit(n, %u): %u (0x%X)\n", k, a, a);
    printf("After clear_bit(n, %u): %u (0x%X)\n", k, b, b);
    printf("After toggle_bit(n, %u): %u (0x%X)\n", k, c, c);
    printf("check_bit(n, %u): %s\n", k, present ? "true" : "false");

    return 0;
}

Sample input:

  • (no input)

Exact output:

n = 41 (0x29)
After set_bit(n, 3): 49 (0x31)
After clear_bit(n, 3): 33 (0x21)
After toggle_bit(n, 3): 33 (0x21)
check_bit(n, 3): true

Why: 1u << 3 is 8. 41|8 = 49, 41 & ~8 = 33, 41 ^ 8 = 33. Bit 3 in 41 is 1, so check_bit is true.

Example 3: Short-circuiting prevents division by zero

Code:

#include <stdio.h>
#include <stdbool.h>

/* Return true if a/b > limit; safe even when b == 0 */
bool ratio_gt_limit(int a, int b, int limit) {
    return (b != 0) && (a / b > limit); // if b==0, right side not evaluated
}

int main(void) {
    int a1 = 10, b1 = 0;
    int a2 = 12, b2 = 3;

    printf("Case1: b1==0, result=%s\n", ratio_gt_limit(a1, b1, 2) ? "true" : "false");
    printf("Case2: 12/3 > 2? result=%s\n", ratio_gt_limit(a2, b2, 2) ? "true" : "false");

    /* Using || to guard an expensive check */
    int x = 5;
    int y = 0;
    if (x == 5 || (y != 0 && x / y > 1)) {
        printf("Short-circuit with || avoids risky RHS\n");
    }

    return 0;
}

Sample input:

  • (no input)

Exact output:

Case1: b1==0, result=false
Case2: 12/3 > 2? result=true
Short-circuit with || avoids risky RHS

Why: && evaluates left to right; when b==0, (a/b > limit) is not executed, preventing a runtime error. || stops when the left operand is true.

Common mistakes

  • Assuming integer division yields a fraction. In C, 7/2 with integers is 3. Use a cast or double operands: (double)7/2 is 3.5.
  • Using uninitialized variables in expressions. This yields indeterminate values and undefined behavior.
  • Modifying the same variable multiple times without defined sequencing, e.g., i = ++i + i++; is undefined behavior. Write side effects in separate statements.
  • Shifting by a negative or too-large count, or shifting negative signed integers: behavior is undefined or implementation-defined. Prefer unsigned for bit shifts and ensure 0 <= k < width.
  • Relying on signed overflow to wrap. Signed overflow is undefined; only unsigned types wrap modulo 2^n.
  • Misplacing parentheses in ternary operator: a ? b : c + d means a ? b : (c + d), but a ? (b : c) + d is invalid; ensure each branch is a single expression as intended.
  • Misunderstanding sizeof: it yields size in bytes and does not evaluate its expression operand (except for VLA-related cases). sizeof x++ does not increment x.
  • Assuming data type sizes (e.g., int is 2 or 4 bytes) or endianness. These are implementation-defined; write portable code.
  • Using , (comma) inside larger expressions without realizing it has the lowest precedence and left-to-right evaluation; this can hide bugs.

For your exam

Typical questions from this topic and what to include:

  • Definitions: Operator, operand, expression, lvalue/rvalue, side effect, precedence, associativity, integer promotions, usual arithmetic conversions, short-circuiting. Write precise one- or two-line definitions.
  • Short notes: Bitwise operators with truth tables for 1-bit cases; increment/decrement differences; difference between logical and bitwise; implicit vs explicit conversions; undefined vs implementation-defined behavior.
  • Diagrams: Precedence ladder diagram with associativity arrows and operator groups (as described above). Label clearly.
  • Programs: Small C programs using arithmetic, logical, and bitwise operators; demonstrate short-circuiting safety; show sizeof result printing and effect of casting. Include clean I/O and exact expected output.
  • Numericals (conceptual): Manually evaluate given expressions step by step using precedence and associativity, stating integer division and promotions; compute bitwise results with binary representation.
  • Derivations/rules: State the usual arithmetic conversions sequence and integer promotions, then apply to sample mixed-type expressions.
  • Pitfalls: Explain with examples: = vs ==, undefined expressions with multiple modifications, and integer division surprises. A full-marks answer is clear, uses correct terminology, shows steps with parentheses to make grouping explicit, cites the rules used (precedence, associativity, promotions), and, for programs, compiles and produces the stated output.

Quick check

  1. What is the value of x after int x = 7; x += 3 * 2 - 4 / 2;?
  2. Does a || b always evaluate b? Why or why not?
  3. For unsigned int n = 16; what is n >> 2 and why?

Answers: 1) x = 7 + (3*2) - (4/2) = 7 + 6 - 2 = 11. 2) No; || short-circuits, so if a is true (nonzero), b is not evaluated. 3) 4 because right shift by 2 divides by 4 for powers of two in unsigned arithmetic, discarding low bits.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?