1

I'm looking few exercise from university about C++ and I found out this exercise:

#include <iostream>
using namespace std;

int x = -2;

int h(int &x) {
    x = 2 * x;
    return x;
}

int g(int f) {
    return x;
}

int &f(int &x) {
    x += ::x; 
    return x;
}

int main() {
    int x = 6;
    f(::x) = h(x);
    cout << f(x) << endl;
    cout << g(x) << endl;
    cout << h(x) << endl;
    return 0;
}

The output of this code is :

24
12
48

Can anyone explain me how do I get this output?

And how does f(::x) = h(x); work?

LogicStuff
  • 19,397
  • 6
  • 54
  • 74
said
  • 29
  • 5

2 Answers2

4
  1. ::x refers to global int x, rather than to local x.

    See: What is the meaning of prepended double colon “::” to class name?

  2. Function signatures differ (either pass x by value or reference). The former makes a copy, later does not and changes on int &x will reflect on whatever x refers to (what you pass as an argument).

    See: What's the difference between passing by reference vs. passing by value?

  3. If you have int & as a return type, you will be able to make changes through this reference it returns to whatever was passed to f (by reference).

Think about how the code works, bearing in mind the aforementioned.

Community
  • 1
  • 1
LogicStuff
  • 19,397
  • 6
  • 54
  • 74
1

Remember that local variables hide global variables? What you have here is that principle in action.

Consider the function

int &f(int &x) {
    x += ::x; 
    return x;
}

Here int &x passed as arguments is local to the function; where as ::x in the function refers to the global variable x.

By the way, :: is called the scope resolution operator and is used for many other purposes as well in C++.

aliasm2k
  • 883
  • 6
  • 12