6

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.

6
  • 3
    I think it's the same as below... 61fecc1. std::initializer_list<int>int.
    – Eljay
    Jun 9 at 10:54
  • the first one should be an array that contains just one element, the second one treats the {1} as an integer initialization and it just sets the value of i_num to it as i_num is declared as int Jun 9 at 10:57
  • 1
    Try auto i_num{1};
    – Quimby
    Jun 9 at 11:00
  • it might be different based on the architecture of the processor or even a micro controller and its compiler.
    – Amir Rasti
    Jun 9 at 11:02
  • 3
    This is the famous change made in C++14. auto i{1}; was changed to be an int, but auto i = {1}; is still an initializer_list. A "good" compromise...
    – BoP
    Jun 9 at 12:38

2 Answers 2

9

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
5

The line auto i_num = {1} defines a variable with type std::initializer_list<int>.
You should have a warning from the compiler about the fact that you are trying to print an initializer list using the %x format.
It prints the address of the first item in the initializer list (not the initializer list address).

auto i_num = {1};
printf("%x\n", i_num); //58a74744
printf("%x\n", &i_num); //58a74730
printf("%x\n", i_num.begin()); //58a74730
1
  • Or part of the address. Or something different entirely, depending on how the platform defines initializer_list. In short, it's at least unspecified, and probably undefined. Jun 9 at 12:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.