Skip to content
C++ Basics: Reset a Value and Keep Its Previous State

C++ Basics: Reset a Value and Keep Its Previous State

November 3, 2026

Use std::exchange to consume a pending count without losing the old value.

Prepare a scratch directory

Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.

Keep the same terminal open. Stop if setup fails, before saving the source:

start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1

Run the example

Save this as exchange-reset-and-return-demo.cpp:

#include <iostream>
#include <utility>

int take_pending(int& pending_count)
{
    return std::exchange(pending_count, 0);
}

int main()
{
    int pending_count = 7;
    const int first_batch = take_pending(pending_count);
    const int second_batch = take_pending(pending_count);
    std::cout << "First batch: " << first_batch << '\n';
    std::cout << "Second batch: " << second_batch << '\n';
    std::cout << "Pending: " << pending_count << '\n';
}

Compile and run it. The program runs only after compilation succeeds:

g++ -std=c++20 -Wall -Wextra -Werror -pedantic exchange-reset-and-return-demo.cpp -o exchange-reset-and-return-demo &&
./exchange-reset-and-return-demo

Observed output:

First batch: 7
Second batch: 0
Pending: 0

Read the result

The first call returns seven and stores zero in pending_count. The next call therefore returns zero. The operation expresses both parts of the state transition in one return statement.

Apply it carefully

std::exchange is not an atomic synchronization operation. Protect shared mutable state with appropriate synchronization, or use an atomic object and its member exchange when that matches the design. For class types, moving the previous value or assigning the replacement can throw. This integer example has neither ownership nor exception complications. Unlike swap, exchange does not store the old value in a second caller-supplied variable.

The C++ working draft describes the relevant rules. This example uses C++20 facilities; the current working draft also documents later additions.

Clean up

Remove only the source and executable created here, then return to the starting directory:

rm -- exchange-reset-and-return-demo.cpp exchange-reset-and-return-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directory

If the directory is not empty, inspect its remaining contents before removing anything else.

Acknowledgements

This post was created with assistance from AI.

Last updated on