Question

If a function returns an int, can it be assigned by an int value? I don't see it makes too much sense to assign a value to a function.

int f() {}

f() = 1;

I noticed that, if the function returns a reference to an int, it is ok. Is it restricted only to int? how about other types? or any other rules?

int& f() {}

f() = 1;
Was it helpful?

Solution

The first function returns an integer by-value, which is an r-value. You can't assign to an r-value in general. The second f() returns a reference to an integer, which is a l-value - so you can assign to it.

int a = 4, b = 5;

int& f() {return a;}

...
f() = 6;
// a is 6 now

Note: you don't assign a value to the function, you just assign to its return value. Be careful with the following:

int& f() { int a = 4; return a; }

You're returning a reference to a temporary, which is no longer valid after the function returns. Accessing the reference invokes undefined behaviour.

OTHER TIPS

It's not limit to int only, but for the primitive types there no point in doing it. It's useful when you have your classes

If a function returns an object by value, then assignment is possible, even though the function call is an rvalue. For example:

std::string("hello") = "world";

This creates a temporary string object, mutates it, and then immediately destroys it. A more practical example is:

some_function(++list.begin());

You could not write list.begin() + 1, because addition is not possible on list iterators, but increment is fine. This example does not involve assignment, but assignment is just a special case of the more general rule "member functions can be called on rvalues".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top