reference in function

J

jimmy

hello ,

I want to create a new function that way:

void foo(int &x,int &y=0) {}

I mean that, I would use it both the way foo(x) and foo(x,y).

but the complier says that was invalid.

how can i make it .

thank u.
 
I

Ian Collins

jimmy said:
hello ,

I want to create a new function that way:

void foo(int &x,int &y=0) {}
A non-const reference requires an lvalue, 0 isn't one. This is because
your code might try and change the value referenced.

You have to use a const&.
 
J

Jerry Coffin

hello ,

I want to create a new function that way:

void foo(int &x,int &y=0) {}

I mean that, I would use it both the way foo(x) and foo(x,y).

but the complier says that was invalid.

A couple of possibilities. One is to simply overload the
function:

void foo(int &x, int &y) {
// whatever
}

void foo(int x) {
int y = 0;
foo(x, y);
}

Another is to create a variable and pass a reference to
it:

int default = 0;

void foo(int &x, int &y = default) {
// whatever
}

Just keep in mind that this probably doesn't make a whole
lot of sense. The primary reason to pass an int by
reference is so the function can modify the variable that
was passed -- and modifying 'default' won't accomplish
much (and may cause your program to do something strange
when/if default is changed to some non-zero value.
 
K

Kai-Uwe Bux

jimmy said:
hello ,

I want to create a new function that way:

void foo(int &x,int &y=0) {}

I mean that, I would use it both the way foo(x) and foo(x,y).

but the complier says that was invalid.

how can i make it .

What about

void foo ( int & x, int & y ) {}

void foo ( int & x ) {
int dummy = 0;
foo( x, dummy );
}



Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top