Advertisement
Beginner C++, Type Deduction & auto

What is the difference between auto x = {…} and auto x{…}?

Short answer

auto x = {1, 2, 3}; deduces std::initializer_list . In C++17, auto x{1}; (single element, direct-list-init) deduces int, while auto x{1, 2}; is ill-formed.

Save C++ mock interview
Advertisement
AModel answer
auto x = {1, 2, 3}; deduces std::initializer_list<int>. In C++17, auto x{1}; (single element, direct-list-init) deduces int, while auto x{1, 2}; is ill-formed. This special case exists because braced initialization with auto was a common source of surprise; knowing it avoids accidentally getting an initializer_list.
auto a = {1, 2, 3}; // std::initializer_list<int>
auto b {5};         // int (C++17)
Real-world example
A developer is surprised that auto x = {1} is an initializer_list, not an int—this rule explains why.
Likely follow-ups
  • What does auto x = {1,2} deduce? | What changed in C++17?
Related topics