Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ auto keyword when using initialize list

Tags:

c++

I have a question for using of key word auto when I run code below:

auto i_num = {1};
printf("%x", i_num);//61fecc
return 0;

I think it's the same as below but not:

int i_num = {1};
printf("%x", i_num);//1
return 0;

Can anyone explain this difference to me? It seems auto i_num and int i_num define different things.

like image 576
Wason Avatar asked Aug 30 '26 23:08

Wason


1 Answers

One is an integer other one an std::initializer_list<int>:

auto var_auto = {1};
std::cout << typeid(var_auto).name() << std::endl;//St16initializer_listIiE

int var_int = {1};
std::cout << typeid(var_int).name() << std::endl;//i

The expression {1} defines an initializer list. This is assigned to the auto variable. Remove the "=" to get your expectation.

auto var_auto{1};
std::cout << typeid(var_auto).name() << std::endl;//i
like image 181
Marco F. Avatar answered Sep 02 '26 14:09

Marco F.