Avirup Mullick
Avirup Mullick

Reputation: 75

Return value int&

I have a code like this.

#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}

The output I am getting is

0
1 1
1 2

Now the function abc returns an integer reference. So the statement int f=abc(); should point integers f and c to the same address. But why the statement f++ is not affecting the value of c?

Upvotes: 0

Views: 158

Answers (5)

Deepam Sarmah
Deepam Sarmah

Reputation: 155

In following code: int f = abc() f is a copy of the value of c, these two values are distinct. When you perform ++f you are incrementing the copy f which will have no effect on c. When you do the following: int &f = abc() you are creating a reference variable f which is bound to the value of c and hence as f is an alias for the variable c, any changes made to f are made to c.

Upvotes: 0

Jagath01234
Jagath01234

Reputation: 169

Yes abc() returns a reference. But f is just an integer variable. Therefore whatint f=abc() does is assigning the value of c to f. When you call f++ it only change the f variables value. It does not change the value of c. because f is not a pointer.

Upvotes: 0

Zephyr Guo
Zephyr Guo

Reputation: 1173

int &f = abc();

Because your f is not a reference.It just a variable that be assigned a value of c.You should write it look like above.

Upvotes: 2

James Adkison
James Adkison

Reputation: 9602

int f = abc();
^^^ // This type is 'int' not 'int&'

You're type for f is int which is no the same as int& and results in creating a copy. Therefore, instead of f being a reference to c it is a separate and distinct value that is initialized to the same value as stored in c when it is returned from abc.

Upvotes: 0

Amit
Amit

Reputation: 46323

That's because while abc() returns an int by reference, f doesn't "grab" this reference, but rather grabs the value the returned reference points to. If you want f to grab the reference, you need to define it as a reference type.

Do it like this:

#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int &f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}

Upvotes: 1

Related Questions