references/ref1-bad.cc - A function that attempts to return references to local variables. | Lecture 2 - slide 15 : 29 Program 4 |
// Annother illustration of C++ reference parameters. // Attempting to return a reference to a local variable. Compiles with warnings. #include <iostream> #include <string> int& f(bool b){ int i = 5, j = 10; std::cout << "i: " << i << " "; std::cout << "j: " << j << std::endl; if (b) return i; // error (warning) Reference to local variable returned. else return j; // error (warning): Reference to local variable returned. } int main() { using namespace std; int a, b; a = b = 0; f(true) = 15; f(false) = 20; f(true) = 25; }