Exchanges the positions of the top two elements on the operand stack.
1. Description
The exch operator swaps the top two elements on the operand stack. This is one of the most frequently used stack manipulation operators, essential for reordering operands before applying binary operations.
This is a Level 1 operator, available in all PostScript implementations.
3. Parameters
any1-
Any PostScript object of any type. Will become the second element after exchange.
any2-
Any PostScript object of any type. Will become the top element after exchange.
5. Examples
5.1. Basic Usage
% Simple exchange
1 2 exch % Stack: 2 1
% Exchange strings
(hello) (world) exch % Stack: (world) (hello)
5.2. Preparing for Division
% Compute 10 / 2 (result should be 5)
2 10 % Stack: 2 10
exch % Stack: 10 2
div % Stack: 5.0
6. Advanced Examples
6.1. Conditional Exchange
% Exchange only if first is greater than second (sort)
/conditionalExch { % a b -> min max
2 copy lt { % If a < b
% Already in order, do nothing
} {
exch % Swap them
} ifelse
} def
% Usage
5 3 conditionalExch % Stack: 3 5 (sorted)
2 8 conditionalExch % Stack: 2 8 (already sorted)
7. Edge Cases and Common Pitfalls
Using exch with fewer than two elements on the stack causes a stackunderflow error.
|
9. PostScript Level
Available in: PostScript Level 1 and higher
This is a fundamental operator available in all PostScript implementations.
10. Error Conditions
stackunderflow-
There are fewer than two elements on the operand stack when
exchis executed.clear 5 exch % ERROR: stackunderflow
11. Performance Considerations
The exch operator is extremely fast and has negligible performance impact. It’s a basic stack operation with O(1) constant time complexity. Use it freely without performance concerns.
12. Best Practices
-
Use for binary operations:
exchis essential when operands are in the wrong order for binary operations likesub,div,atan -
Combine with dup: The pattern
dup … exchis very common for operations that need the same value twice -
Consider roll for multiple elements: If you’re exchanging more than two elements,
rollmight be more appropriate -
Document stack effects: When using
exchin procedures, clearly document the before/after stack state -
Avoid redundant exchanges: Two consecutive
exchoperations are a no-op
13. See Also
-
Operators Overview - Understanding PostScript operators
-
Stack Operations Guide - Stack manipulation tutorial
-
Stack Manipulation - All stack operators