// This program illustrates the difference between pointers and references. // // When you have a pointer, use * to get to the location/value it point to. // // When you have a reference, you don’t need *. A reference is an alias // for a location. It’s sort of like a pointer with auto-*. // // You can change where a pointer points to. // A reference, however, can never be “re-seated”. Once it’s declared, // it is forevermore an alias for that location. #include using namespace std; int main() { double data[] = {1.2, 3.4, 5.6, 7.8}; double *p = &data[1]; // p points to 3.4 double &r = data[2]; // r is an alias for data[2] cout << "p points to " << *p << '\n'; // Note the star cout << "r refers to " << r << '\n'; // Note the lack of star p = &data[0]; // Reassign the pointer cout << "p now points to " << *p << '\n'; r = 6.66; // change data[2] to 6.66 r = data[3]; // change data[2] to 7.8 // The previous line did NOT reseat r. It just modified data[2], // to which r must always refer. cout << "r refers to " << r << '\n'; return 0; }