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.

2. Syntax

any1 any2 exch any2 any1

2.1. Stack Effect

Table 1. Before Execution
Position Content

Top

any2 (any type) - Second element to exchange

Top-1

any1 (any type) - First element to exchange

Table 2. After Execution
Position Content

Top

any1 - Originally second element, now on top

Top-1

any2 - Originally top element, now second

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.

4. Return Values

The same two objects, but with their positions swapped.

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

5.3. Reordering for Subtraction

% Compute 10 - 3 (not 3 - 10)
3 10            % Stack: 3 10
exch            % Stack: 10 3
sub             % Stack: 7

5.4. Working with Dictionaries

% Store value in dictionary with key on top
/mydict 10 dict def
42              % Value to store
/answer         % Key
exch            % Stack: /answer 42
mydict 3 1 roll % Stack: /answer mydict 42
put             % Store answer: 42 in mydict

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)

6.2. Three-Element Rotation

% Rotate three elements: a b c -> c a b
/rotate3 {      % a b c -> c a b
    exch        % a c b
    3 1 roll    % c a b
} def

% Usage
1 2 3 rotate3   % Stack: 3 1 2

6.3. Duplicate and Exchange Pattern

% Common pattern: duplicate top, then get second
/dupExch {      % a b -> a b a
    dup         % a b b
    3 1 roll    % b a b
    exch        % b b a
    pop         % b a
} def

7. Edge Cases and Common Pitfalls

Using exch with fewer than two elements on the stack causes a stackunderflow error.

7.1. Stack Underflow

% BAD: Not enough elements
clear 5         % Stack: 5
exch            % ERROR: stackunderflow

7.2. Excessive Exchange

% BAD: Multiple exchanges cancel out
1 2 exch exch   % Stack: 1 2 (back where we started)
% Better to not exchange at all
Remember that two consecutive exch operations cancel each other out. If you find yourself doing this, reconsider your stack management strategy.

7.3. Type Confusion

% Be careful with type-sensitive operations
10 (hello) exch % Stack: (hello) 10
add             % ERROR: typecheck (can't add string and number)
  • dup - Duplicate top element before exchanging

  • roll - General stack rotation for multiple elements

  • index - Access elements deeper in the stack

  • pop - Remove top element

  • copy - Copy multiple stack elements

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 exch is 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

  1. Use for binary operations: exch is essential when operands are in the wrong order for binary operations like sub, div, atan

  2. Combine with dup: The pattern dup …​ exch is very common for operations that need the same value twice

  3. Consider roll for multiple elements: If you’re exchanging more than two elements, roll might be more appropriate

  4. Document stack effects: When using exch in procedures, clearly document the before/after stack state

  5. Avoid redundant exchanges: Two consecutive exch operations are a no-op

12.1. Clear Stack Effect Comments

% Good practice: document stack effects
/hypotenuse {   % x y -> sqrt(x^2 + y^2)
    dup mul     % x y^2
    exch        % y^2 x
    dup mul     % y^2 x^2
    add         % x^2+y^2
    sqrt        % result
} def

13. See Also


Back to top

Copyright © 2025 Ribose. PostScript is a trademark of Adobe. Distributed under the MIT License.