简体   繁体   中英

C++ function output

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?

  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.

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++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM