C++ reference syntax
Which is the correct way to specify a reference. I know both works with the compiler, but wanted to know the correct way since I have seen both in code bases.
void Subroutine(int &Parameter)
{
Parameter=100;
}
OR
void Subroutine(int&am开发者_如何学运维p; Parameter)
{
Parameter=100;
}
There is no 'correct' way, in the same way like there is no 'correct' way to place your parentheses and brackets. It's a matter of style and preference.
It's more important to be consistent.
When it comes to pointers, C programmers tend to write int *i
which reads "evaluating *i
yields an int
". This is not possible with references. If you write int &i
, evaluating &i
does not yield an int, but rather a pointer to an int, because &
has different meanings in declarations and expressions.
That's why I prefer to declare reference variables as int& i
, because i
is a reference to an int.
It's a matter of preference, both are correct, personally I nowadays like to write it as type&
I think the two are functionally identical. I personally prefer int& Parameter since it makes more sense to me -- i.e. a variable named Parameter
is of type reference-to-int
, whereas int &Parameter doesn't immediately make that connection to me. Most examples I've seen use the int& form as well. (i.e. see http://www.cprogramming.com/tutorial/references.html).
That's code style issue, no one is good or bad, correct or wrong.
I use this:
int & a;
int * b;
Too many spaces (any maybe a little confusing with binary operator & and *) but it looks clear to me.
As long as consistent, whatever your style is correct.
精彩评论