0

I don't own a book on C++ and cant afford one, and cant seem to find a decent post (or a good google result) regarding the topic.

So what is the difference? and what would best practice be for writing this?

Object* myObject;

vs.

Object *myObject

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Send_Help
  • 37
  • 7
  • 2
    Personal preference – Joe Jan 27 '22 at 20:23
  • Here's a round about answer as well as explaining a gotcha that can come from this confusion: https://stackoverflow.com/questions/398395/why-is-the-asterisk-before-the-variable-name-rather-than-after-the-type – Corey Ogburn Jan 27 '22 at 20:23
  • in general whitespace in c++ is ignored – Alan Birtles Jan 27 '22 at 20:25
  • [This is a little bit out of date](https://isocpp.org/tour) and it's terse as hell but if you have and cannot get a reputable C++ text, it's better than nothing. The information is high quality, it's just hard to parse and light on explanation. Use it in conjunction with the [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) and you'll have an easier time. – user4581301 Jan 27 '22 at 20:35
  • As per [C++ FAQ](https://isocpp.org/wiki/faq/style-and-techniques#whitespace), Sutter & Stroustrup suggest the first one is preferential for C++. – Eljay Jan 27 '22 at 21:54

1 Answers1

1

When declaring a variable, these two are essentially the same. Best practices depend on your style guide, and when contributing to a larger codebase, consistency with existing style.

However, there's one subtlety that leads me to prefer the second option Object *myObject in cases where this does not clash with an existing style guide. Specifically, the following code declares an Object pointer, and an Object (not a pointer):

Object *obj1, obj2;

When the asterisk is attached to the name, this is a bit clearer - at a rapid glance, the following equivalent code could mislead someone (especially a newer programmer who isn't aware of this gotcha) into thinking two pointers are being declared:

Object* obj1, obj2;

Furthermore, I probably wouldn't recommend mixing types like this anyway, and if I did want to declare two pointers then

Object *obj1, *obj2; // declarations look consistent

seems a tad cleaner than

Object* obj1, *obj2; // need to use second style anyway

or

Object* obj1, * obj2; // ???
nanofarad
  • 40,330
  • 4
  • 86
  • 117