This code:
int a = 5;
int& b = a;
b = 7;
cout << a;
prints out 7, and replacing int& b
with int &b
also prints out 7.
In fact so does int&b
and int & b
.
I tested this kind of behavior with a simple class as well. In general, does it ever matter whether the ampersand is placed relative to the type and identifier? Thanks.
No, there is absolutely no difference except coding style. I think the main argument about coding style is that this declaration:
declares
a
as anint&
andb
as anint
.It doesn't make a difference to the compiler which way it is written. Which is correct is a matter of code style.
It doesn't make any difference because c/c++/java these languages are not space sensitive.
The example posted it does not matter, but there are cases where it does:
As always, whitespace doesn't matter.
In C-like languages, whitespace mostly doesn't matter.
All versions you listed parse as the same three tokens:
int
&
b
so they mean the same to the compiler.
The only time whitespace matters is when it separates two alphanumeric tokens, and even then the amount and type of whitespace doesn't matter, as long as there is some. But any sort of punctuation always becomes a separate token from alphanumerics, no whitespace is needed.
So your code can become as short as:
The remaining whitespace is needed.
These are two functionally equivalent declarations:
Associating the
&
or*
with the type name reflects the desire of the programmer to have a separate pointer type. However, the difficulty of associating the&
or*
with the type name rather than the variable is that, according to the formalC++
syntax, neither the&
nor the*
is distributive over a list of variables. Thus, easily creating misleading declarations. For example, the following declaration creates one, not two, integer references.Here,
b
is declared as an integer (not an integer reference) because, when used in a declaration, the&
(or*
) is linked to the individual variable that it precedes, not to the type that it follows. The problem with this declaration is that, visually both a and b seem to be of reference types, even though, onlya
is a reference, thus visual confusion not only misleads noviceC++
programmers, but occasionally experienced programmers too.It doesn't matter whether you write
int &a
orint& a
for aC++
compiler. However, to avoid confusion,&
and*
should be associated with variable rather than type.