Arrays, Type Aliases, and Structured Bindings
Variables and Data Types

1.8 Arrays, Type Aliases, and Structured Bindings

C-style arrays are part of C++ and appear in low-level and interoperability code, but they decay to pointers easily and do not carry their size into most function calls. Prefer std::array for fixed-size owned storage and std::span later in the course for a non-owning view.

Fixed-size storage with std::array

std::array<T, N> keeps elements contiguously, knows its size, supports iterators, and works with the standard algorithms. Unlike a raw array parameter, it cannot silently lose its extent.

#include <array>
#include <cstddef>

int main() {
    std::array<int, 3> samples{4, 8, 15};
    return samples.size() == 3 && samples[1] == 8 ? 0 : 1;
}
Prefer std::array for a fixed-size owned collection.

Give difficult types a meaningful name

A using alias improves readability without creating a distinct type. Use it for a domain-relevant spelling, but use a wrapper type when the compiler should prevent mixing two values that happen to have the same representation.

using UserId = unsigned long long;

UserId currentUser() {
    return 42;
}
A type alias documents an intended unit.

Unpack structured results

Structured bindings, introduced in C++17, let you unpack a pair, tuple, array, or aggregate. Use const auto& when you need to observe an existing object without copying it; plain auto creates new values or moves from an initializer as usual.

#include <utility>

std::pair<int, bool> parsePort() {
    return {9000, true};
}

int main() {
    const auto [port, valid] = parsePort();
    return valid && port == 9000 ? 0 : 1;
}
Structured bindings unpack a pair.

Practice: rewrite a raw int values[4] as std::array<int, 4>, then write a function that accepts it by const reference and returns its largest element.

Chapter 1 Knowledge CheckQuestion 1 of 6

Why should a header usually avoid `using namespace std;`?

Finished reading this lesson?