1

What is the meaning of saying

fun()=30;
count<<fun();

Function definition is:

int &fun()
{
    static int x = 10;
    return x;
}
Danis Fermi
  • 590
  • 1
  • 6
  • 17
  • 1
    This is related to [this](http://stackoverflow.com/questions/18964801/assigning-value-to-function-returning-reference) question – Lorenzo Belli Dec 09 '16 at 16:34
  • Another duplicate: http://stackoverflow.com/questions/36477542/what-does-int-foo-mean-in-c?rq=1 – Fabio says Reinstate Monica Dec 09 '16 at 16:37
  • It's a classic anti pattern in that the normal sense of a function is that it returns something that is a result of its parameters sometimes mixed with non-mutable state information. Most people that are C++ programmers recognize it as a function returning a non-const ref. It's good practice that functions that return a ref should return a const ref. – doug Dec 09 '16 at 17:20
  • 1
    Note that returning a non-`const` reference isn't _always_ an anti-pattern. Valid use cases would be [providing a non-`const` version of an operator such as `operator[]`](http://ideone.com/ywGPpN) (like what `std::vector` does, for example), or in the Builder pattern (where the [`Builder` class' setters return `Builder&`, so that they can be chained together](http://ideone.com/ThvJEB)). – Justin Time - Reinstate Monica Dec 09 '16 at 18:36

1 Answers1

7
int& fun();

The return type of fun() is an integer reference.

fun() = 30

assign the value 30 to the integer referenced by the return value of fun().

Which integer?

int &fun()
{
    static int x = 10; // <-- this one
    return x;
}
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142