Predict the console output of a function with two defer blocks before its return.
Read the function below. It registers two defer blocks, then prints and returns a value, and the caller prints the returned value.
Assume nothing throws and the program compiles cleanly.
func load() -> Int {
defer { print("A") }
defer { print("B") }
print("body")
return 42
}
print(load())
Determine the exact console output, line by line, and explain the ordering.
defer blocks run as the scope exits — here at return — in LIFO order, so the last-registered runs first. It prints body, then B, then A; the returned 42 prints last, after load() returns. Output — body, B, A, 42.
- ✗Expecting
deferblocks to run in written (FIFO) order rather than LIFO - ✗Thinking a
deferfires at its own line rather than at scope exit - ✗Believing a normal
returnskips thedeferblocks
- →In what order do three
deferblocks in the same scope execute? - →Does a
deferstill run if the function exits by throwing an error?
The defer blocks are queued as they are reached and drained when the scope exits — at the return — in reverse registration order (LIFO). B was registered after A, so B runs first. load() fully returns 42 before the outer print(load()) can print it, so 42 is last.
func load() -> Int {
defer { print("A") } // registered 1st → runs last
defer { print("B") } // registered 2nd → runs first
print("body")
return 42
}
print(load())
// body
// B
// A
// 42
Output, line by line:
body
B
A
42