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?
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.
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.
Literally no difference. Just a stylistic preference. The same is true of where you put the pointer.
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;
andint *p;
is not about right and wrong, but about style and emphasis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With