How can I set the default value for a reference variable when I use as the argument of a function in C++?
Asked
Active
Viewed 2,461 times
0
-
This makes no sense. Rethink your design. – Baum mit Augen Jul 09 '16 at 13:50
-
You can't for a reference, but you can for a reference to a constant, e.g. `const double&`. If you can't have a `const` variable because you are supposed to change it, then maybe you should consider returning the value instead? – Some programmer dude Jul 09 '16 at 13:51
-
You can't do this with non-const reference. Does `d1` need to be modified inside `test()`? – songyuanyao Jul 09 '16 at 13:51
-
2Provide an added overload: `void test(int j) { double d1 = 0.0; test(j, d1); }`, and lose the default-value in the two parameter version. – WhozCraig Jul 09 '16 at 14:00
2 Answers
3
There's no way to provide a reference to a temporary value, unless you use the move operator, or a const
reference:
void test (int j, double && d1=0.0)
// ^^ Move
{
//my codes
}
void test (int j, const double & d1=0.0)
// ^^^^^ Extend lifetime
{
//my codes
}
The fact you declare a reference (output) parameter for this function, indicates that the function doesn't makes sense without passing an output parameter, so a default value is completely off (What should a call test(j);
actually do?).
What you might have meant is to reset the output parameter when entering the function:
void test (int j, double & d1) {
d1 = 0.0; // << Assure a certain output
//my codes
}

πάντα ῥεῖ
- 1
- 13
- 116
- 190
-
@SaeidMo7 Well, what do you want to achieve in the _`// my codes`_ part actually? – πάντα ῥεῖ Jul 09 '16 at 14:45
-
-
@SaeidMo7 You probably oversimplified your example. Try to elaborate more about your actual use case in your question and provide a [MCVE] please. – πάντα ῥεῖ Jul 09 '16 at 15:10
-
@πάνταῥεῖ Your answer about making the input reference a `const` will work in my case, aside from the fact that my referenced value is not a simple built in type. How would this work for any general type `T`? Doing `const T &var = 0` raises an error: `An rvalue expression of type "int" cannot be converted to type "const T &".` – pretzlstyle May 14 '18 at 20:42
2
You can only do that for a const &
, not for a non-const one. A const reference can bind to a temporary, a non-const reference cannot.

Jesper Juhl
- 30,449
- 3
- 47
- 70
-
I want to change the value of d1 in the function, so const & it does not work. – SaeidMo7 Jul 09 '16 at 13:56
-
1
-
1@SaeidMo7 you're not changing the "value" of `d1`. It is a reference, and as such you want to change the value of what it references, but that is only plausible if there is indeed something to reference, which there isn't in your default case. Thusly, design = broken. – WhozCraig Jul 09 '16 at 13:59