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

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

Susan Sarandon
Release: 2024-11-29 17:54:11
Original
756 people have browsed it

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

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

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

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

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!

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