I am trying to declare a pointer variable initialized to "nullptr" using "auto" keyword but getting error.
Kindly help me how could we do it.
1 2 3
auto num = int{0}; //this is valid variable declaration.
auto ptr = int*{nullptr}; //this is invalid.
auto *ptr1 = int*{nullptr}; //this is also invalid.
Whats wrong with int* ptr = nullptr;
auto is cool because I don't need to type out std::vector<int>::iterator it = vec.begin() like the old days. But this isn't the most shining example of use.
Hi Poteto, there's nothing wrong with int* ptr = nullptr;,
but auto <var> = <type>{initial_value>}; has an inherent benefit that the "var" can never be left
uninitialized because this syntax of variable declaration makes supplying initial value mandatory.
1 2
int* ptr; //allowed, ptr might have garbage
auto ptr = int*; // not allowed, there is no way "rhs" of this expression can be left without inital value.
I found that using auto pervasively wasn't worth the extra effort required to debug. Now I only use it when I don't care to repeat types, or when I don't know them. YMMV.
Me too. Being able to know what type an object is by looking at where it is declared is very valuable to me. auto is helpful to me only when it's not known at compile-time, or when it can be easily inferred from the rest of the same line of code (such as in a range-based for loop, or the creation of an iterator).