`auto` — C++ Keyword
`auto` — C++ Keyword
The auto keyword in C++: type deduction for variables, return types, and parameters.
`auto` — C++ Keyword
The auto keyword in C++: type deduction for variables, return types, and parameters.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
autoInstructs the compiler to deduce the type of a variable from its initializer, a function's return type from its return statement, or (C++20) a function parameter type.
auto name = expression; // deduce type
auto name = {list}; // deduces std::initializer_list
const auto& name = expression; // deduce const reference
auto&& name = expression; // forwarding reference
auto func() -> TrailingType; // trailing return type
auto func() { return expr; } // deduced return type (C++14)
void func(auto x); // abbreviated function template (C++20)
#include <print>
#include <vector>
#include <map>
int main() {
auto i = 42; // int
auto d = 3.14; // double
auto s = std::string{"hello"};
std::vector<int> v = {1, 2, 3};
for (const auto& x : v) {
std::print("{} ", x); // 1 2 3
}
std::println();
std::map<int, std::string> m = {{1, "one"}, {2, "two"}};
for (auto& [k, val] : m) { // structured binding
std::println("{}: {}", k, val);
}
}
auto strips top-level const and references; use const auto& or auto& to retain them.auto and decltype(auto) differ: decltype(auto) preserves reference and const qualifiers exactly.autoint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}