TeachMeBitcoin

OP_MAX - Returning the Larger Value

From TeachMeBitcoin, the free encyclopedia Reading time: 1 min

17. OP_MAX — Returning the Larger Value

Opcode Reference

Opcode:     OP_MAX
Hex:        0xA4
Decimal:    164
Input:      a b
Output:     max(a, b)

Overview

OP_MAX pops the top two stack elements and pushes whichever is the larger numeric value.

Stack Examples

Input: [b=10, a=3]  → OP_MAX → [10]
Input: [b=3, a=10]  → OP_MAX → [10]
Input: [b=5, a=5]   → OP_MAX → [5]
Input: [b=-1, a=-5] → OP_MAX → [-1]

Bitcoin Core Implementation

case OP_MAX:
{
    if (stack.size() < 2)
        return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
    CScriptNum bn1(stacktop(-2), fRequireMinimal);
    CScriptNum bn2(stacktop(-1), fRequireMinimal);
    popstack(stack);
    popstack(stack);
    stack.push_back((bn1 > bn2 ? bn1 : bn2).getvch());
}
break;

Use Cases

OP_MAX enforces a minimum floor — by taking the maximum of a value and a floor, you ensure the result is never below the floor:

<user_value> <floor> OP_MAX
→ result is at least <floor>

Combined with OP_MIN, you can clamp a value to a range:

<value> <floor> OP_MAX <ceiling> OP_MIN
→ result is clamped to [floor, ceiling]
☕ Help support TeachMeBitcoin

TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!