Home > Backend Development > C++ > Why Can\'t C Functions Have Default Values for Non-Const Reference Parameters?

Why Can\'t C Functions Have Default Values for Non-Const Reference Parameters?

Susan Sarandon
Release: 2024-11-28 12:16:15
Original
483 people have browsed it

Why Can't C   Functions Have Default Values for Non-Const Reference Parameters?

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);
Copy after login

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
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template