Reputation: 2604
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.
Upvotes: 17
Views: 19581
Reputation: 5694
These are two functionally equivalent declarations:
int& a; // & associated with type
int &a; // & associated with variable
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 formal C++
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.
int& a, b;
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, only a
is a reference, thus visual confusion not only misleads novice C++
programmers, but occasionally experienced programmers too.
It doesn't matter whether you write int &a
or int& a
for a C++
compiler. However, to avoid confusion, &
and *
should be associated with variable rather than type.
Upvotes: 3
Reputation: 616
It doesn't make any difference because c/c++/java these languages are not space sensitive.
Upvotes: 1
Reputation: 53097
In general, does it ever matter whether the ampersand is placed relative to the type and identifier?
The example posted it does not matter, but there are cases where it does:
int & a, b; // b is not a ref
int const * a; // pointer to const int
int * const a; // const pointer to int
As always, whitespace doesn't matter.
Upvotes: 7
Reputation: 283961
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:
using namespace std;int a=5;int&b=a;b=7;cout<<a;
The remaining whitespace is needed.
Upvotes: 11
Reputation: 12994
It doesn't make a difference to the compiler which way it is written. Which is correct is a matter of code style.
Upvotes: 1
Reputation: 225281
No, there is absolutely no difference except coding style. I think the main argument about coding style is that this declaration:
int& a, b;
declares a
as an int&
and b
as an int
.
Upvotes: 21