Passing Parameters by Reference with Default Values in C
In C , when passing parameters by reference, it is not possible to assign a default value to the parameter. This raises an error when attempting to declare functions with default values for reference parameters. For instance, the following code will result in an error:
virtual const ULONG Write(ULONG &State = 0, bool sequence = true);
Error encountered:
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
Resolution
Default values can only be assigned to const references, not non-const references. This is due to C 's restriction that a temporary (such as the default value) cannot be bound to a non-const reference.
As a workaround, 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 approach has limited practical applicability.
The above is the detailed content of Why Can\'t C Functions Have Default Values for Non-Const Reference Parameters?. For more information, please follow other related articles on the PHP Chinese website!