This page is a placeholder. All examples on this page are currently AI-generated and are not correct. This documentation will be completed in the future with accurate, tested examples.
Overview
Opcode: 0x03
Introduced: Frontier (EVM genesis)
SUB performs subtraction on two 256-bit unsigned integers with wrapping underflow semantics. When the result is negative (first operand < second operand), it wraps around modulo 2^256 to produce a large positive value.
This operation is essential for decrements, difference calculations, and implementing signed arithmetic in smart contracts.
Specification
Stack Input:
Stack Output:
Gas Cost: 3 (GasFastestStep)
Operation:
Behavior
SUB pops two values from the stack (a first, then b), computes a - b, and pushes the result. Underflow wraps around without exceptions:
- If
a >= b: Result is the mathematical difference
- If
a < b: Result wraps to 2^256 - (b - a)
No exceptions are thrown for underflow. The result always fits in 256 bits.
Examples
Basic Subtraction
Underflow Wrapping
Large Underflow
Identity Element
Self-Subtraction
Gas Cost
Cost: 3 gas (GasFastestStep)
SUB shares the lowest gas tier with ADD, making it one of the cheapest operations:
Comparison:
- ADD/SUB: 3 gas
- MUL/DIV/MOD: 5 gas
- ADDMOD/MULMOD: 8 gas
- EXP: 10 + 50 per byte
SUB and ADD have identical gas costs due to similar computational complexity in hardware.
Edge Cases
Maximum Underflow
Zero Subtraction
Operand Order Matters
Stack Underflow
Common Usage
Balance Updates
Loop Counters (Decrement)
Difference Calculations
Range Checks
Safe vs Unchecked
Solidity 0.8.0+:
Implementation
Testing
Test Coverage
Security
Underflow Vulnerabilities
Classic vulnerability (pre-0.8.0):
Attack scenario:
Famous exploit: BatchOverflow (2018)
Safe Patterns (Pre-0.8.0)
Modern Solidity (0.8.0+)
Comparison Patterns
Benchmarks
SUB performance characteristics:
Execution time (relative):
- SUB: 1.0x (same as ADD)
- MUL: 1.2x
- DIV: 2.5x
Gas efficiency:
- 3 gas per 256-bit subtraction
- ~333,333 subtractions per million gas
- Identical cost to ADD
Optimization:
References