Primitive Operations & Cost Model
What Operations Are Allowed on Primitive Data Types
Read aloud is unavailable in this browser.
The Building Blocks of Computation
Every algorithm ever written—from the simplest loop to the most sophisticated machine learning model—ultimately reduces to a sequence of operations on primitive data types. Addition, comparison, assignment, bit manipulation: these atomic operations form the vocabulary from which all computational behavior is constructed.
Understanding what operations are permitted on primitive types, and how they behave, is not merely a matter of language syntax. It is the foundation upon which we reason about algorithms, analyze complexity, and make engineering decisions that scale across billions of operations.
By the end of this page, you will have a complete mental model of the operations available on primitive data types: arithmetic, relational, logical, bitwise, and assignment operations. You'll understand not just what these operations do, but why they exist, how they map to hardware, and what guarantees they provide.
The Concept of a Primitive Operation
Before enumerating specific operations, we must establish what qualifies as a primitive operation in the context of data structures and algorithms.
Definition:
A primitive operation is an atomic computational step that:
- Operates directly on primitive data types (integers, floating-point numbers, characters, booleans)
- Executes in bounded, constant time regardless of the magnitude of operands
- Maps closely to hardware instructions available on the underlying processor
- Cannot be decomposed into simpler computational steps at the algorithmic level
This definition has profound implications. When we analyze algorithm complexity, we count primitive operations. When we claim an operation is O(1), we're asserting it can be treated as a primitive operation for analytical purposes.
At the hardware level, even 'primitive' operations involve multiple steps: fetching operands from registers, performing ALU operations, storing results. However, algorithmic analysis abstracts these details away, treating the entire sequence as a single atomic step. This abstraction is both the power and the limitation of complexity analysis—a theme we'll explore throughout this module.
Why This Matters:
Consider the difference between adding two integers and concatenating two strings:
a + b(integers): Two fixed-size operands combine in a single CPU instructions1 + s2(strings): Every character must be copied; time grows with string lengths
The first is primitive; the second is not. Confusing the two leads to catastrophic performance misjudgments. Engineers who treat string concatenation in a loop as 'simple addition' discover O(n²) behavior where they expected O(n).
This distinction—primitive versus composite operations—is the first mental tool you need for algorithmic reasoning.
Categories of Primitive Operations
Primitive operations can be systematically classified into five fundamental categories, each serving distinct computational purposes. Understanding these categories provides a complete vocabulary for describing algorithmic behavior.
| Category | Purpose | Operand Types | Result Type |
|---|---|---|---|
| Arithmetic | Mathematical computation | Numeric (int, float) | Numeric |
| Relational | Value comparison | Numeric, char | Boolean |
| Logical | Boolean algebra | Boolean | Boolean |
| Bitwise | Binary manipulation | Integer | Integer |
| Assignment | Value transfer | Any primitive | None (side effect) |
Each category represents a different axis of computation:
- Arithmetic operations transform numerical values
- Relational operations establish ordering and equality
- Logical operations combine truth values
- Bitwise operations manipulate binary representations
- Assignment operations move data between memory locations
Together, these five categories are computationally complete for primitive types—any transformation you need to perform on primitive data can be expressed as a composition of these operations.
Arithmetic Operations
Arithmetic operations perform mathematical computations on numeric primitive types (integers and floating-point numbers). They form the computational core of most algorithms.
- •Addition (+) — Combines two numeric values. For integers, this is exact (within range). For floats, subject to precision limits.
- •Subtraction (-) — The inverse of addition. Same precision considerations apply.
- •Multiplication (*) — Scales values. Can quickly exceed representable ranges, making overflow a key concern.
- •Division (/) — Integer division truncates; floating-point division yields approximations. Division by zero is undefined.
- •Modulo (%) — Returns the remainder after integer division. Crucial for cyclic computations, hashing, and range constraining.
- •Negation (unary -) — Flips the sign of a value. For two's complement integers, negating MIN_VALUE overflows.
Arithmetic operations on fixed-size integers can overflow (exceed maximum) or underflow (fall below minimum). When 2,147,483,647 + 1 becomes -2,147,483,648 in 32-bit signed integers, algorithms that assumed monotonic growth break catastrophically. Understanding these boundaries is essential for correct algorithm design.
Hardware Mapping:
Each arithmetic operation maps to dedicated CPU instructions:
| Operation | x86 Instruction | ARM Instruction |
|---|---|---|
| Addition | ADD | ADD |
| Subtraction | SUB | SUB |
| Multiplication | IMUL / MUL | MUL |
| Division | IDIV / DIV | SDIV / UDIV |
Modern CPUs execute these instructions in 1-4 clock cycles, making them truly constant-time at the hardware level. This direct mapping is why we treat arithmetic as primitive operations in algorithm analysis.
Among arithmetic operations, division is notably slower—often 10-40x more clock cycles than addition or multiplication. Experienced engineers replace division with multiplication by reciprocals or bit shifts when possible. Understanding operation costs at this level separates performant code from naive implementations.
Relational Operations
Relational operations compare two values and produce a boolean result. They are the foundation of branching (if-else decisions) and ordering (sorting, searching).
- •Equal to (==) — Returns true if both operands have identical values. For floats, exact equality is dangerous due to precision.
- •Not equal to (!=) — The logical negation of equality.
- •Less than (<) — Establishes strict ordering. Essential for sorting algorithms.
- •Greater than (>) — The complement of less-than-or-equal.
- •Less than or equal (<=) — Non-strict ordering, includes equality.
- •Greater than or equal (>=) — The complement of less-than.
The Role of Comparisons in Algorithms:
Relational operations are the decision points in algorithms. Consider binary search:
if (arr[mid] < target)
search right half
else if (arr[mid] > target)
search left half
else
found!
Every comparison eliminates half the search space. The logarithmic efficiency of binary search directly depends on relational operations being O(1). If comparisons were expensive, the entire analysis would change.
Comparison-Based Lower Bounds:
A profound theoretical result: any comparison-based sorting algorithm requires at least O(n log n) comparisons in the worst case. This lower bound assumes each comparison is primitive. The insight extends throughout algorithm theory—the number of primitive comparisons often determines algorithmic limits.
Comparing floating-point numbers for equality is notoriously problematic. Due to representation errors, 0.1 + 0.2 == 0.3 evaluates to false in most languages. Engineers use epsilon-based comparisons: abs(a - b) < epsilon instead of a == b. This is a semantic detail with deep algorithmic implications.
Logical Operations
Logical operations implement Boolean algebra, operating on truth values to produce new truth values. They are the combinators that allow complex conditions to be built from simple comparisons.
- •AND (&&) — Returns true only if both operands are true. Models conjunction: 'A and B must both hold.'
- •OR (||) — Returns true if at least one operand is true. Models disjunction: 'A or B (or both) must hold.'
- •NOT (!) — Inverts a boolean value. The fundamental negation operation.
- •XOR (^) — Returns true if exactly one operand is true. Useful for toggling and difference detection.
| A | B | A AND B | A OR B | NOT A | A XOR B |
|---|---|---|---|---|---|
| false | false | false | false | true | false |
| false | true | false | true | true | true |
| true | false | false | true | false | true |
| true | true | true | true | false | false |
Short-Circuit Evaluation:
A critical semantic detail: most languages implement short-circuit evaluation for AND and OR:
A && B: If A is false, B is never evaluated (result is already false)A || B: If A is true, B is never evaluated (result is already true)
This is not merely an optimization—it changes program semantics. Code like ptr != null && ptr->value == target relies on short-circuiting to avoid null dereference. Understanding short-circuit behavior is essential for both correctness and performance.
De Morgan's Laws:
Two fundamental equivalences govern logical transformation:
NOT (A AND B) ≡ (NOT A) OR (NOT B)NOT (A OR B) ≡ (NOT A) AND (NOT B)
These laws are invaluable for simplifying complex conditions and are used extensively in query optimization, compiler transformations, and algorithm design.
Bitwise Operations
Bitwise operations manipulate integers at the level of individual bits—the raw binary representation. They provide direct control over data representation and enable powerful low-level optimizations.
- •Bitwise AND (&) — Sets each bit to 1 only if both corresponding bits are 1. Used for masking and flag checking.
- •Bitwise OR (|) — Sets each bit to 1 if at least one corresponding bit is 1. Used for setting flags.
- •Bitwise XOR (^) — Sets each bit to 1 if the corresponding bits differ. Used for toggling and cryptography.
- •Bitwise NOT (~) — Inverts every bit. One's complement operation.
- •Left Shift (<<) — Shifts bits left, filling with zeros. Equivalent to multiplication by powers of 2.
- •Right Shift (>>) — Shifts bits right. Arithmetic vs logical shift depends on language and signedness.
Practical Applications:
Bitwise operations appear throughout systems programming and algorithm optimization:
| Use Case | Technique | Example |
|---|---|---|
| Multiply by 2ⁿ | Left shift | x << 3 = x * 8 |
| Divide by 2ⁿ | Right shift | x >> 2 = x / 4 |
| Check if bit set | AND with mask | x & (1 << k) |
| Set a bit | OR with mask | `x |
| Clear a bit | AND with inverted mask | x & ~(1 << k) |
| Toggle a bit | XOR with mask | x ^ (1 << k) |
| Check if power of 2 | AND with predecessor | x & (x-1) == 0 |
| Swap without temp | Triple XOR | a ^= b; b ^= a; a ^= b |
These patterns appear constantly in competitive programming, embedded systems, and performance-critical code. The XOR swap, for instance, exchanges two values using only bitwise operations—no temporary variable needed.
Many interview problems test bit manipulation skills: counting set bits, finding the single non-duplicate element (XOR all values), or determining if a number is a power of 2. These problems reveal whether a candidate understands data at its most fundamental level—the bit.
Assignment Operations
Assignment operations transfer values between memory locations. Unlike other operations that produce values, assignment produces a side effect: modifying the state of memory.
- •Simple Assignment (=) — Copies the value from right operand to left operand. The fundamental state mutation.
- •*Compound Assignment (+=, -=, =, /=, %=) — Combines arithmetic with assignment.
x += 5is equivalent tox = x + 5. - •Bitwise Compound Assignment (&=, |=, ^=, <<=, >>=) — Combines bitwise operations with assignment.
- •Increment/Decrement (++, --) — Special case of adding/subtracting 1. Pre vs post variants have subtle semantic differences.
The Semantics of Assignment:
For primitive types, assignment means copying the value:
int a = 5;
int b = a; // b gets a COPY of 5
b = 10; // a is still 5
This is value semantics—each variable holds its own independent copy. This contrasts sharply with reference semantics for non-primitive types, where assignment copies a reference (pointer) rather than the data itself.
Memory Model Implications:
At the hardware level, assignment involves:
- Evaluating the right-hand side expression
- Storing the result in the memory location of the left-hand side
For primitives fitting in CPU registers (most integers, all floats), this is a single MOV instruction. The operation is O(1) because the data size is fixed and bounded—we copy the same number of bytes regardless of the value.
The difference between ++i (pre-increment) and i++ (post-increment) matters: pre-increment returns the new value; post-increment returns the old value and then increments. While functionally equivalent in isolation, post-increment technically creates a temporary copy, though modern compilers optimize this away for primitives.
KEEP LEARNING
Keep learning for free.
Read the complete lesson, save your notes and pick up where you left off with a free account. No card needed.