← Back to C++ Course | Chapter 16: Modern C++ | Lesson 7 of 9

C++ Structured Bindings

What is Structured Binding?

Structured bindings, introduced in C++17, let you unpack multiple values from a struct, pair, tuple, or array into individually named variables in a single declaration, instead of accessing each member one at a time through dot or index syntax.

Example: What is Structured Binding?

cpp
#include <iostream>
#include <utility>

int main() {
	std::pair<int, int> point(3, 4);
	auto [x, y] = point;
	std::cout << x << "," << y << std::endl;
	return 0;
}

Binding to Struct Members

For a struct, the syntax auto [a, b] = myStruct; unpacks its public members in declaration order into the variables a and b. The number of names inside the brackets must exactly match the number of members being unpacked, or the compiler rejects it.

Example: Binding to Struct Members

cpp
#include <iostream>

struct Point { int x; int y; };

int main() {
	Point p{3, 4};
	auto [a, b] = p;
	std::cout << a << "," << b << std::endl;
	return 0;
}

Binding to Arrays

The same bracket syntax works on a fixed-size C-style array -- auto [x, y, z] = myArray; unpacks each of its three elements into separate variables, which is often more readable than repeatedly indexing the array by number.

Example: Binding to Arrays

cpp
#include <iostream>

int main() {
	int arr[3] = {1, 2, 3};
	auto [x, y, z] = arr;
	std::cout << x << " " << y << " " << z << std::endl;
	return 0;
}

Using References in Bindings

By default, structured bindings copy each unpacked value into its new variable, so changes to the bound variable don't affect the original struct or array. Declaring the binding as a reference -- auto& [a, b] = myStruct; -- instead binds directly to the original members, so modifications propagate back.

Example: Using References in Bindings

cpp
#include <iostream>

struct Point { int x; int y; };

int main() {
	Point p{1, 2};
	auto &[x, y] = p;
	x = 100;
	std::cout << p.x << std::endl;
	return 0;
}

Using const References

When you want to unpack values without copying but also want to guarantee they can't be accidentally modified, const auto& [a, b] = myStruct; gives you a read-only reference binding -- the best choice when you're only inspecting a large struct's fields.

Example: Using const References

cpp
#include <iostream>

struct Point { int x; int y; };

int main() {
	Point p{5, 6};
	const auto &[x, y] = p;
	std::cout << x << " " << y << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.