Question: A very subtle but important distinction in modern C++ is the difference between a pointer and a reference. Pointers are a C concept, while references



A very subtle but important distinction in modern C++ is the difference between a pointer and a reference. Pointers are a C concept, while references are a modern C++ concept. References were added to the language to give you the efficiency of pointers, while reducing the chance for error. A reference has the following characteristics: 1. Cannot be null (in C++, NULL is gone and nullptr denotes a null pointer value) 2. Always points to a memory location 3. Cannot be modified to point to a different memory location Here's some code using pointers: int x = int y int* p int* q. 10; 20; &x; &y; = X++; q++; Exercise #1: Using the code on the previous page, suppose the variable a lives at memory address 2000, and b lives at the memory address 4000. The size of an integer is 4 bytes. After execution of the above code, draw boxes for each of the 4 variables a, b, c and d, and show their integer values. For cand d, draw an arrow to where it points in addition to the value of the pointer. Now consider this code using references: int e = 30; int f = 40; int& g = e; int& h = f; f++; g++; Exercise #2: Suppose the variable e lives at memory address 6000, and flives at the memory address 8000. The size of an integer is 4 bytes. After execution of the above code, draw boxes for each of the 4 variables e, f, g and h, and show their integer values. For g and h, draw an arrow to where it points in addition to the value stored in the reference location. Finally, consider the following code fragment: int a = 90; int b = 80; int* c = &a; int* d = &b; int e = 70; int f 60; int& g = e; int& h = f; C = d; g = h; Exercise #3: Draw boxes for each of 8 variables, and after execution of the above code show the contents of each box. Assume a lives at memory address 2000, b lives at 4000, e lives at 6000, and flives at 8000. In addition, draw arrows from c, d, g and h to where they point
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
