Search code examples
c++referencereturn-value

how is INT returned as INT& in c++?


am a c++ beginner and this code really confused me:

int global = 100;
int& setGlobal()
{
    return global;    
}
int &a=setGlobal() ;

int main(void){
    a=a+5;
    std::cout<<global<<std::endl;
}

The return type of setGlobal is int& , but global is an int.

  • Please explain to me how does that work?
  • Shouldn't it be return &global ?

The code that i understand is like this:

  int global = 100;
  int& x=global;

  int& setGlobal()
  {
    x+10;
    return x;    
  } 
  int main(void){
    x=x+10;
    std::cout<<global<<std::endl;
    }

Maybe my problem is with references.


Solution

  • A return type of T& gets you the reference of the returned object of type T.

    In your case

    int& setGlobal()
    {
        return global;    
    }
    

    returns a reference (int&) to global. Basically an alias, another way to access the same variable.

    This means that

    int &a=setGlobal() ;
    

    Sets a as a reference to global and any operation on a is reflected on global.

    It should come as no surprise that

    int main(void){
        a=a+5;
        std::cout<<global<<std::endl;
    }
    

    prints 105. a and global are effectively interchangeable in your main scope (because one is an alias of the other).

    If setGlobal returned &global, it would be returning the address of global. The address is the actual location of the variable in memory, it's not an alias. If you wanted to work with pointers, your code would look like this instead:

    #include <iostream>
    
    int global = 100;
    int* setGlobal()
    {
        return &global;    
    }
    int* a=setGlobal() ;
    
    int main(void){
        *a=*a+5;
        std::cout<<global<<std::endl;
    }
    

    Notice how we can't access the contents of global using a directly (it's just an address). We must first dereference it.

    And for good measure, you should also know that, since setGlobal() returns a reference to global in your example, it can be used directly as an lvalue to access global like so:

    setGlobal() += 5;
    

    Putting the above statement just before printing will result in "110" being displayed. Fun stuff! I invite you to read about lvalues and rvalues on your own time as a next step in your C++ journey!