0
#include <iostream>
using namespace std;

void f(const int& x)
{
}

int g()
{
    int x = 0;
    return x;
}

int main() {
    f(g());
} 

If i remove the const from f it doesnt work; What does this mean, is the temporary returned from g a const???

  • 1
    A parameter of `const int&` says "take the parameter by reference, and I promise not to modify it". `int&` says "take the parameter by reference, and I'll be modifying it". It doesn't make sense to *modify* a temporary — that could only lead to subtle programming bugs, which is why it isn't allowed. – Eljay Jun 10 '22 at 12:57
  • 2
    Nitpick before I finish looking into it: why `using namespace std;`? Nothing from `std` is even used here, and there's a litany of reasons to avoid it. See [Why is using namespace std considered a bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Rogue Jun 10 '22 at 12:57
  • 1
    Note that you can however declare `void f(int&& x)` (since C++11). This is a *rvalue reference*, used in the **move** semantics. This is advanced feature however, that a beginner should not worry about yet. – prapin Jun 10 '22 at 13:25
  • @Eljay -- the issue is more subtle; temporaries of class types can be modified (but still can't be passed by non-const reference). So `struct X { void modify_me(); }; X f() { return X(); }; f().modify_me();` is okay. – Pete Becker Jun 10 '22 at 14:05

0 Answers0