0

Most examples of auto use the = operator.

#include <iostream>

int main()
{
    auto a = 1;
    std::cout << a << '\n';
}

Why don't they use the uniform initializer like this?

#include <iostream>

int main()
{
    auto a {1};
    std::cout << a << '\n';
}

Is there any advantage or disadvantage of using one syntax over another while using the auto keyword?

2

Well, there's one reason. Until C++17, auto a {1}; did the wrong thing (probably). See, the assumption was that if you were using a braced-init-list to initialize a placeholder-declared variable, then you wanted to create an initializer_list<T>. So unless you wanted a to be an initializer_list<int> containing 1 value...

So only in C++17 does auto a {1}; actually do the thing you (probably) wanted: a will be a genuine int. Of course, auto a = {1}; will still be an initializer_list<int>, because that's totally obvious, right?

So yeah, probably best to stick with auto a = 1;.

  • I tried the second example with auto a {1} with clang++ -std=c++11 -Wall -Wextra -pedantic foo.cpp && ./a.out and I don't get a compiler error. It produces the output 1. It seems to contradict your first point. – Lone Learner May 25 '18 at 2:55
  • @LoneLearner: The behavior of compilers is irrelevant; only the standard matters. And if you look in the C++11 standard, in [dcl.spec.auto]/6, you will see... that you (and Clang) are absolutely right ;) – Nicol Bolas May 25 '18 at 3:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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