Continuation passing style is a style of functional programming, in which every function takes the continuation waiting for its return value as an explicit argument. Instead of returning a value to its caller directly, the function returns the result of applying the continuation to what it would normally have returned.
Here is an example in Scheme:
Normal programming style | Continuation passing style
|
(define (mysqrt x) (sqrt x))
|
(define (mysqrt x k) (k (sqrt x)))
|
(+ (mysqrt 4) 2)
|
(mysqrt 4 (lambda (x k) (k (+ x 2))))
|
Continuation passing style can be used to implement continuations in a functional language that does not feature first class continuations but has first class functions.
As continuation passing style renders return values virtually useless, it can also be used to eliminate the need for a stack and return values entirely. Several interpreters for functional programming languages use this concept internally.