Strange use of pointers and functions = SO confused!

Hi, I was shown this code by a friend and (though I'm not entirely that experienced with c++) I had never seen or known anything such as function()=6 to be possible. Especially in this context!

I've searched google but to no avail, is this a documented technique or is it just a funny result of dodgy programming and memory allocation?

Here's the code:

#include <iostream>
using namespace std;

int gg=0;
int gb=10;
int h = 0;
int& function()
{
return gg;
}

int main() {
cout<<gg;
function()=6;
cout<<gg;
return 0;
}

I compiled this with g++ and the result from running is 06, by looking at the code I assumed it wouldn't have even compiled and even by some magic it did I assumed the result would be 00!

If you replace "return gg;" with say "return h;" you'll get 0. So why and how is function() tied to the variable gg?

Any help from someone better than me would be great! Thanks!
Adem
closed account (z05DSL3A)
function() returns a reference to gg, so when function()=6 gets evaluated, the reference to gg gets resolved and then 6 is assigned to that reference thus gg becomes 6.
I see, I assumed it was referencing but what I don't understand is how "int& function()" references gg? How would I make it reference say h?

Thankyou by the way!
gg is a global variable.
function() return a reference (which is sort of an alias) to gg.
Therefore, function()=6; can be replaced by gg=6;.
Never mind, I realised my own stupidity and now the code makes sense. HA.

Effectively whilst playing around with it I was changing "return gg;" to "return h;" but making the epic error of not replacing gg with h in the cout lines. Now it makes so much more sense lol.

Thanks very much again!
Adem
Last edited on
When you call function, conceptually, the function name is "replaced" with the return value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int gg=0;

int& function()   // this function returns a reference
{
  return gg;   // returns a reference to 'gg'
}

int main()
{
  // this line:
  function()=6;

  // is functionally equivilent to this:
  int& reference_to_gg = function();
  reference_to_gg = 6;


If you want to refer to another variable, simply have 'funciton' return something else. Whatever it returns is what gets referred to.

edit -- blah I'm too slow XD
Last edited on
Topic archived. No new replies allowed.