Default Value for Referenced Parameter in C
When passing a parameter by reference in C , can you specify a default value for it?
Consider the following function declaration:
virtual const ULONG Write(ULONG &State = 0, bool sequence = true);
Attempting to compile this code results in an error:
error C2440: 'default argument' : cannot convert from 'const int' to 'unsigned long &' A reference that is not to 'const' cannot be bound to a non-lvalue
The Answer
Default values can only be assigned to constant references, not non-constant references. This is because C prohibits binding a temporary (in this case, the default value) to a non-constant reference.
To work around this constraint, you can use an actual instance as the default value:
static int AVAL = 1; void f( int &x = AVAL ) { // stuff } int main() { f(); // equivalent to f(AVAL); }
However, this method has limited practical applicability.
The above is the detailed content of Can C Functions Have Default Values for Non-Const Reference Parameters?. For more information, please follow other related articles on the PHP Chinese website!