CS 70

References Exercise 2: Assigning to a Reference

  • LHS Cow speaking

    Here's another one to try...

Consider the following code snippet:

int a = 2;
int& b = a;
int c = 31;
a = 8;
cout << a << " " << b;
b = c;
cout << " " << a << " " << b;

Can you guess what might happen?

Remember the key idea of references: when we have int& x = y;, xand y are just two names for the same thing.

Don't worry about being right or wrong. Just think it through and give the answer that makes the most sense to you!

Draw a memory diagram of this snippet and then give the printed output.

Key Idea: A reference never changes its referent. Once it is initialized, the reference and the referent are interchangeable.

  • Duck speaking

    What if I—?

  • LHS Cow speaking

    Never.

  • Duck speaking

    Okay, but—

  • LHS Cow speaking

    Ne. Ver.

  • RHS Cow speaking

    At initialization you give the reference its referent. After that, the reference and its referent are just both names for the same data!

(When logged in, completion status appears here.)