xlii
An Overture to C Programmers
You declare
a_ref
as a reference to
int a
u
. There is no way to reseat
a_ref
to point to another
int
. You might try to reseat
a
with
operator=
v
, but
this actually sets the value of
a
to the value of
b
instead of setting
a_ref
to
reference
b.
After the snippet is run both
a
and
b
are equal to
100
, and
a_ref
still points to
a
. Listing 9 contains equivalent code using pointers instead.
int main() {
int a = 42;
int* a_ptr = &a;
u
int b = 100;
*a_ptr = b;
v
}
Listing 9: An equivalent program to Listing 8 using pointers
Here, you declare the pointer with a
*
instead of a
&
u
. You assign the
value of
b
to the memory pointed to by
a_ptr
v
. With references, you don’t
need any decoration on the left side of the equal sign. But if you omit the
*
in
*a_ptr
, the compiler would complain that you’re trying to assign an
int
to
a pointer type.
References are just pointers with extra safety precautions and a sprinkle
of syntactic sugar. When you put a reference on the left side of an equal sign,
you’re setting the pointed-to value equal to the right side of the equal sign.
Dostları ilə paylaş: