initializer_list in C++
When you initialize an auto variable with a braced list, the C++ compiler deduces its type as std::initializer_list.
If you initialize a variable declared with auto using a braced list, the C++ compiler deduces the type of the variable as std::initializer_list.
#include <iostream>
#include <initializer_list>
using namespace std;
int main()
{
auto a = {2,1,3,1};
// a is an initializer_list<int>
for(auto el: a){
cout<< el << endl;
}
return 0;
}
All elements must have the same type. auto a = {1, 2.5}; doesn’t compile, because the compiler can’t decide between int and double.
Update (2026): Be careful with direct list initialization. Since C++17 (N3922, which compilers also applied to C++11/14 mode),
auto b{1};is just anint, not aninitializer_list<int>, andauto c{1, 2};is an error. Only the=form,auto a = {...};, gives you aninitializer_list.