std::array

What Is get() in C?

C has no get() function for arrays. In C++, get() means std::get, which reads one std::array element by a fixed, compile-time index. Examples follow below.

On this page
  1. The short answer
  2. How std::get works in C++
  3. Why the index must be a constant
  4. What get might mean in a C tutorial
  5. Other types that work with std::get

The short answer

C has no get() function for arrays. In C++, get() usually refers to std::get, a function template that returns one element of an std::array. You write the index in angle brackets, such as std::get<0>, and the index must be known at compile time.

How std::get works in C++

#include <array>
#include <iostream>

int main() {
    std::array<int, 3> scores{90, 75, 88};

    std::cout << std::get<0>(scores) << '\n';  // 90
    std::get<2>(scores) = 95;                  // changes the third element
    std::cout << scores[2] << '\n';            // 95
}

The output is:

90
95

std::get returns a reference to the element, so assigning to the result changes the array. The last two lines show this.

Why the index must be a constant

The index is a template argument, so the compiler has to know it before the program runs. Both of these lines fail to compile:

int i = 1;
std::cout << std::get<i>(scores);  // i is not a compile-time constant
std::cout << std::get<3>(scores);  // 3 is out of range for an array of 3

If the index changes while the program runs, use scores[i] instead. The [] operator takes any index, but it does not check the range.

What get might mean in a C tutorial

If you saw get in a C tutorial, it probably referred to an input function, not an array function. Two examples are getchar(), which reads one character, and fgets(), which reads a line of text into a buffer you provide.

The older gets() function was unsafe because it could write past the end of its buffer. It was removed from the C standard in C11.

C does not have std::array, so it has no direct equivalent of std::get. To read an element of a C-style array, use arr[i].

Other types that work with std::get

std::get also works with std::pair, std::tuple and std::variant. For a pair or a tuple, you pass an index, or a type if that type appears only once. For a variant, you can pass the index or the type. If you use tuples, the same syntax applies there, and tuple in c explains how they are built.

Since C++17, you can also unpack an std::array with structured bindings. This can be easier to read than several std::get calls:

auto [first, second, third] = scores;  // copies the three elements into new variables

The complete guide to std::array

std::array in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

Unary Operators in C++

Learn what unary operators in C++ are, from the one-operand symbols like !, ~, ++ and * to prefix vs postfix, precedence and common mistakes, with examples.