C - Operators

Operators in C

Operators are special symbols that perform operations on variables and values. C provides a rich set of operators for arithmetic, comparison, logic, bitwise, assignment, and more.

Learning Objectives

  • Use arithmetic, relational, logical, bitwise, and assignment operators correctly.
  • Explain truthiness in C (0 is false; nonzero is true).
  • Understand operator precedence at a practical level.

Prerequisites

Types of Operators

  • Arithmetic (+ - * / %)
  • Relational (< > <= >= == !=)
  • Logical (&& || !)
  • Bitwise (& | ^ ~ << >>)
  • Assignment (= += -= *= /=)
  • Increment/Decrement (++ --)
  • Conditional (?:)

Examples

#include <stdio.h>

int main(void) {
    int a = 5, b = 2;
    printf("a + b = %d\n", a + b);      // 7
    printf("a == b = %d\n", a == b);    // 0 (false)
    printf("a > b = %d\n", a > b);      // 1 (true)
    printf("a && b = %d\n", a && b);    // 1 (true)
    printf("a | b (bitwise) = %d\n", a | b); // 7
    a += 3; // a = 8
    printf("a after += 3: %d\n", a);
    int max = (a > b) ? a : b;
    printf("max = %d\n", max);
    return 0;
}

Common Pitfalls

  • Confusing assignment (=) with equality (==).
  • Assuming true is 1 specifically; any nonzero is true.
  • Forgetting that && and || short-circuit.

Checks for Understanding

  1. What is the result of 5 / 2 in C? Why?
  2. When does a && b evaluate b?
Show answers
  1. It’s 2 (integer division truncates).
  2. Only if a is nonzero (true); otherwise it short-circuits.

Practice

  1. Write an expression using the conditional operator that returns the absolute value of x.
  2. Use bitwise operators to test whether an integer is odd or even.

Summary

Operators are fundamental to writing expressions and logic in C programs. Keep a mental model of precedence and use parentheses to make intent clear.