| references/ref1-better.cc - Ditto - handling the problem by making the local variable static. | Lecture 2 - slide 15 : 29 Program 5 |
// Annother illustration of C++ reference parameters.
// Returns a reference to local a static variable. Strange, but compiles and runs as expected.
#include <iostream>
#include <string>
int& f(bool b){
static int i = 5, j = 10;
std::cout << "i: " << i << " ";
std::cout << "j: " << j << std::endl;
if (b)
return i;
else
return j;
}
int main()
{
using namespace std;
int a, b;
a = b = 0;
f(true) = 15; // 5 10. Then assigning 15 to i.
f(false) = 20; // 15 10. Then assigning 20 to j.
f(true) = 25; // 15 20. Then assigning 25 to i.
}