6

I'm trying to learn the basics of C++. The book I'm reading uses the following syntax:

func(int& x);

On the internet, I mostly see the following syntax:

func(int &x);

Both seem to do exactly the same. Is there any difference?

Willem-Aart
  • 2,200
  • 2
  • 19
  • 27

3 Answers3

12

Literally no difference. Just a stylistic preference. The same is true of where you put the pointer.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Although you'll read about it if you click through to your link, perhaps you should add here the bit about being mislead to believe adding the asterisk next to the type makes all of the variables pointers. – David Vereb Sep 29 '15 at 19:26
  • 2
    @DavidVereb: Or just do as Bjarne recommends: "Declaring one name per declaration minimizes the problem". – Christian Hackl Sep 29 '15 at 19:28
  • "Just a stylistic preference" – not only, it's also about emphasis. – Emil Laine Sep 29 '15 at 19:34
  • 1
    @zenith ... which would be a style preference. As far as the compiler cares, they are identical. – Cory Kramer Sep 29 '15 at 19:35
2

See the answer to the Is int* p; right or is int *p; right? FAQ on Bjarne Stroustrup's website. It's for pointers, but what he writes equally holds for references:

Both are "right" in the sense that both are valid C and C++ and both have exactly the same meaning. [...] The choice between int* p; and int *p; is not about right and wrong, but about style and emphasis.

Christian Hackl
  • 27,051
  • 3
  • 32
  • 62
-1

I prefer int& x. This way the reference becomes part of the type, it's an "int reference" called x, instead of "int, reference of x"

I find that thinking of "int reference" as a discrete type makes it less confusing, but to the compiler it's the same thing.

ventsyv
  • 3,316
  • 3
  • 27
  • 49
  • 3
    This does not answer OP's question, this is merely providing your opinion/preference. – Cory Kramer Sep 29 '15 at 19:24
  • @CoryKramer I'm already thinking about closing the question as _"opinion based"_ or finding a good duplicate. – πάντα ῥεῖ Sep 29 '15 at 19:26
  • @πάνταῥεῖ The question itself is not opinion-based per se. The answer to their question is "no there isn't a difference". It does seem that there are some duplicates, or at least very closely related questions. – Cory Kramer Sep 29 '15 at 19:27
  • It does answer it actually and gives some background why one way is (slightly) better (in my opinion). – ventsyv Sep 29 '15 at 19:29
  • @ventsyv: The ampersand doesn't become part of the type. Given `int& a, b;` are both `a` and `b` references? – Blastfurnace Sep 29 '15 at 19:41
  • @Blastfurnace That's unfortunate artifact due to backward compatibility with C which binds the ampersand to the name but putting the emphasis on "a of type X" (being int& or int* or whatever) is still beneficial. The multi variable declaration is confusing no matter where you put the ampersand. – ventsyv Sep 29 '15 at 19:56