2
#include <type_traits>

int main()
{
    int n;

    auto* p1 = &n;
    auto  p2 = &n;

    static_assert(std::is_same_v<decltype(p1), decltype(p2)>); // ok
}

Any difference between auto* p = &n and auto p = &n? or just a coding style issue?

xmllmx
  • 39,765
  • 26
  • 162
  • 323

2 Answers2

4

Any difference between auto* p = &n and auto p = &n? or just a coding style issue?

In your example, where n is an int, the difference is coding style.

However, if n is an instance of a struct or class type, that provides a unary operator&(), then there is a difference. auto *p = &n will be diagnosed as an error if that overloaded operator& returns any non-pointer type. auto p = &n will only be diagnosed as an error if the operator&() returns void. This can be useful (in the sense that it is better for the compiler to diagnose problems early) if subsequent code relies on &n giving a pointer.

Admittedly, overloading operator&() is a relatively rare (and risky) use case, and overloading to return a non-pointer type is quite rare. However, real-world examples are given here and here.

Peter
  • 35,646
  • 4
  • 32
  • 74
1

Any difference between auto* p = &n and auto p = &n?

No difference.

or just a coding style issue?

Yes, for some it may be clearer with auto* p1 = &n; that it's a pointer.

Note, however, the cpp core guideline seems to favour later/simpler style auto p2 = &n; perhaps because it's consistent with the usage of smart pointer - which doesn't need any * to start with, example:

auto p = make_shared<X>(2);
artm
  • 17,291
  • 6
  • 38
  • 54