0
void subscriberCallback(const std_msg::UInt16& msg)

void subscriberCallback(const std_msg::UInt16 &msg)

Are these the same thing? Why is the ampersand listed after the data type instead of before the variable?

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Related: https://stackoverflow.com/questions/398395/why-is-the-asterisk-before-the-variable-name-rather-than-after-the-type – Passerby Mar 14 '22 at 03:57
  • 7
    They are the same thing. – Icemanind Mar 14 '22 at 03:57
  • 4
    Yes, they're the same. And you'll find countless Internet debates about which one is better. Pick one style and stick with it. – Silvio Mayolo Mar 14 '22 at 03:59
  • 1
    It doesn't matter where it is placed. I prefer the first one – smac89 Mar 14 '22 at 04:00
  • _"Why is the ampersand listed after the data type instead of before the variable?"_ - they do the same thing but people have different preferences. One argument for the former is that the ampersand is not _after_ the data type. It's part of the data type. – Ted Lyngmo Mar 14 '22 at 04:02
  • Whitespace in general doesn't matter unless it's splitting one token into two or merging two into one. – chris Mar 14 '22 at 04:06
  • The two lines you describe are equivalent to the compiler. The difference between them is stylistic (some people insist that the first is better, and other people insist the second is better, and religious flame wars have been fought over such disagreements). Whitespace in C++ separates tokens. As a rule of thumb: an arbitrary amount (zero or more characters) of whitespace can be introduced between any two valid tokens and not change the meaning. Also, your terminology is wrong - this is not a reference operator. – Peter Mar 14 '22 at 04:13
  • @Peter ok. Can you tell me what it is then? – Josh Kindhart Mar 14 '22 at 04:27
  • you can also do `std_msg::UInt16 & msg` but you will get hate mail for doing it – pm100 Mar 14 '22 at 04:59
  • @JoshKindhart It's a declaration of a reference. In this case, `const std_msg::UInt16 &msg` (irrespective of where the whitespace is) declares `msg` as a `const` reference to a `std_msg::UInt16`. The entire line declares a function that accepts that type of argument, and returns `void`. – Peter Mar 14 '22 at 05:07

0 Answers0