Variables, references and pointers - Write the function set (…) so that the following code works correctly I have following homework exercise from lecture &quot;Variables, references and pointers&quot;:

Write the function set (...) so that the following code works
correctly:
int x = 3;
set(x) = 3;
cout &lt;&lt; x &lt;&lt; endl;  // writes 0
set(x) = 4;
cout &lt;&lt; x &lt;&lt; endl;  // writes 3
set(x) = 5;
cout &lt;&lt; x &lt;&lt; endl;  // writes 4


This is my solution:
#include &lt;iostream&gt;

using namespace std;

int &amp; set(int &amp; num);

int main(void) {
    int x = 3;
    set(x) = 3;
    cout &lt;&lt; x &lt;&lt; endl;  // wypisze 0
    set(x) = 4;
    cout &lt;&lt; x &lt;&lt; endl;  // wypisze 3
    set(x) = 5;
    cout &lt;&lt; x &lt;&lt; endl;  // wypisze 4
    return 0;
}

int &amp; set(int &amp; num) {
    static int tmp;
    int &amp; ret = tmp;
    num = ret;
    return ret;
}

What do you think about it?
You have too many variables. The ret is not needed.

Also, for testing I would like to see some actual testing, rather than just printing to the console and letting the user do it:

#include &lt;cassert&gt;

void test_set() {
    int x = 3;
    set(x) = 3;
    assert(x == 0);
    set(x) = 4;
    assert(x == 3);
    // etc.
}


(Or, you could use an actual unit testing framework. But assert works for this simple case.)