2

I'm new to C++, while I'm learning pass by reference I realized that I can't create a reference to a number directly, it has to be a variable. But if I define a function which accepts const reference, I can pass numbers in it.

int SumVal(const int& a, int b)
{
    return a + b;
}

As far as I understand, I can pass a number directly like SumVal(1, 2) if the function declared with a const reference because I'll NOT be able to change the reference so the number(or variable) no matter what. The compiler knows this and doesn't complain about it.

But if I define it with normal reference like int SumVal(int& a, int b) I have the chance to change the passed variable inside the function so If I pass a number into this function, the compiler will complain about this.

So I would like to ask that my approach is correct or non-sense.

Thank you for your comments in advance.

(You can also check it out CB Bailey's this answer about pass by reference/value difference)

Enlico
  • 23,259
  • 6
  • 48
  • 102
Ermanas
  • 43
  • 6
  • 1
    https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects This might be a better duplicate, with some of the philosophy behind why you can pass rvalues to functions expecting a const lvalue reference. – Nathan Pierson Jan 31 '22 at 07:28
  • Ahh I couldn't find how to describe it more simple actually, thank you for mentioning the old questions @NathanPierson I'll check it out. I just understand it's the same thing with `const int& x = 1` :) – Ermanas Jan 31 '22 at 07:43

1 Answers1

1

Yes. It's because a const reference can bind to an r-value, but normal reference can't