Michael posted:
I am a little confused about & and int &. Do they both mean reference?
int a;
int* b= & a ; (& here mean reference of a)
int& b = a ; ( How to understand & precisely here?)
In the English language, you can have two words which are spelled exactly
the same, and which are pronounced exactly the same, but which have
different meaning in different contexts.
(1) indefinitely = not for definite.
indefinitely = forever.
(2) I advised him not to go. = offered counsel
I advised him that his parents had arrived. = informed
In C++, some symbols, keywords and operators have totally different
meanings and effects in different contexts.
In your first example:
int *b = &a;
, the asterisk indicates that you're defining a pointer variable, and the
ampersand acts as the "address of" operator.
In your second example:
int &b = a;
, the ampersand indicates that you're defining a reference.
While the symbols are the same, their meaning is unrelated because the
context is different.
Here's a few examples of different meanings in C++ depending on context:
(1) int *p; /* Defines a pointer variable */
(2) *p = 5; /* Dereferences a pointer variable */
(3) int i = 5 * j; /* Acts as multiplication symbol */
In particular, two symbols have different meaning depending on whether
they're used as part of an object's name, or whether they appear where an
object is NOT being defined (or declared):
(1) int *p; /* Defines a pointer variable */
(2) int &r; /* Defines a reference */
(1) *p = 5; /* This is the "dereferenc e" operator */
(2) p = &i; /* This is the "address of" operator */
--
Frederick Gotham