# std::variant<Types...>::index

> C++ Atlas: `cppatlas.com/w/cpp/utility/variant/index` | Source: https://en.cppreference.com/w/cpp/utility/variant/index | Domain: Utility | Standards: C++17

Returns the zero-based index of the alternative that is currently held by the variant.

## Official Specification Summary (cppreference)

```cpp
constexpr std::size_t index() const noexcept; // (since C++17)
```

Returns the zero-based index of the alternative that is currently held by the variant.

If the variant is `valueless_by_exception`, returns `variant_npos`.

### Example

```cpp
#include <iostream>
#include <string>
#include <variant>

int main()
{
    std::variant<int, std::string> v = "abc";
    std::cout << "v.index = " << v.index() << '\n';
    v = {};
    std::cout << "v.index = " << v.index() << '\n';
}
```

Output:

```text
v.index = 1
v.index = 0
```

### See also

- [`holds_alternative`](https://en.cppreference.com/w/cpp/utility/variant/holds_alternative) (C++17): checks if a `variant` currently holds a given type (function template)
- [`get(std::variant)`](https://en.cppreference.com/w/cpp/utility/variant/get) (C++17): reads the value of the variant given the index or the type (if the type is unique), throws on error (function template)

---
Attribution: content from https://en.cppreference.com/w/cpp/utility/variant/index (cppreference.com), licensed under CC-BY-SA 3.0 and GFDL. Modified: converted to markdown, study notes added. Offline snapshot of 9 February 2025.