Skip to main content
Definition Website Computer and Technology

Continuation-Passing Style

Subject: Computer and Technology noun /kənˌtɪn.juˈeɪ.ʃən ˈpæs.ɪŋ staɪl/ 1 definition

  1. Definition (noun)

    Entry #273 · Updated

    Continuation-Passing Style (CPS) is a programming style and compiler intermediate representation in which control flow is passed explicitly as a first-class continuation function rather than managed implicitly through a call stack. Instead of returning a value to its caller, a CPS procedure accepts an extra continuation parameter—representing the remainder of the computation—and finishes by invoking that continuation as a tail call with its computed result. Because every procedure call in strict CPS occurs in tail position and intermediate subexpressions are bound to explicit parameters, evaluation order is fully specified and non-local control constructs—such as exceptions, coroutines, backtracking, and asynchronous callbacks—can be modeled using ordinary functions. Unlike direct style, which relies on runtime stack frames to track pending evaluation contexts, CPS turns remaining computation into an explicit value so procedures never return to a caller, though practical execution relies on tail-call optimization or closure conversion to avoid stack overflow and excessive closure allocation.

    Common Forms

    • Compiler-IR CPS: A normalized intermediate representation produced by a CPS transformation pass in compilers (such as SML/NJ and Chicken Scheme) that makes evaluation order, jump targets, and variable lifetimes explicit for optimization and code generation.

    • Asynchronous Callback CPS: A manual programming pattern in event-driven runtimes (such as Node.js error-first (err, result) callbacks) where non-blocking I/O functions accept continuation callbacks instead of blocking a thread to return a value.

    • Double-Barreled CPS: A two-continuation variant in which procedures receive separate success and failure continuations, enabling exception handling, parser combinators, and logical backtracking without unwinding a runtime call stack.

    • Delimited CPS: A structured form where continuations capture only a bounded prefix of the remaining computation up to an explicit delimiter (such as shift and reset), powering composable generators, lightweight threads, and algebraic effect handlers.

    Example

    When compiling (+ 1 (square 4)) to C with outer continuation k, a CPS-based Scheme compiler such as Chicken rewrites the expression into (square-cps 4 (lambda (v) (k (+ 1 v)))), packaging the pending addition as an explicit closure. Instead of returning 16 to a caller frame, square-cps invokes that closure as a tail call with v bound to 16, forwarding 17 directly into k.