Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between func(int& x) and func(int &x) in C++ [duplicate]

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?

like image 847
Willem-Aart Avatar asked Sep 29 '15 19:09

Willem-Aart


People also ask

What is the difference between int& and int?

int& is a reference to int variable. Reference is something very close to the pointer. The main difference is that the reference is constant, so it should be assigned immediately after initialization and you can do no pointer arithmetics with reference.

What does int &A mean in C++?

Except, in the function declaration, int &a means you'll be passing in a reference-to-int to the function. &a means "address of a" only when used outside function declarations.


2 Answers

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

like image 102
Cory Kramer Avatar answered Oct 28 '22 19:10

Cory Kramer


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.

like image 2
Christian Hackl Avatar answered Oct 28 '22 19:10

Christian Hackl