How to declare a "nullptr" initialized pointer using "auto" keyword.

Hi everyone,

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. 


I have given examples of what I have tried.

Please help me how could we do it.

Thanks
Last edited on
auto p = static_cast<int*>(nullptr);
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.
Thanks @mbozzi for suggesting a way :).

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. 


just a practice to avoid pitfalls :)

Thanks
Last edited on
That argument comes from Herb Sutter's GotW #94.
https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/

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.
Last edited on
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).
Topic archived. No new replies allowed.