I'm really confused because I can't describe my question well, but I'm sure that many of you will understand me.
#include <iostream>
using namespace std;
void display(int n = 1, char c = '*');
int main()
{
display();
display(5);
display('$');
return 0;
}
void display(int n, char c)
{
for (int i = 1; i <= n; i++)
cout << c;
cout << endl;
}
At display('$')
, I want to pass this char
to its parameter c
and use n
with its default value, which is 1. Can anyone tell me how to do this properly?
You can't as is. When you call a function the parameters get matched from left to right in order. That means display('$');
will give '$'
to n
instead of c
.
What you can do though, at least in this case, is overload the function to do what you want. With
void display(int n, char c);
void display(int n);
void display(char c);
void display();
You can have the void
, int
and char
overload call the main function and hide the fact that your filling in the "blanks". That looks like
void display(int n)
{
display(n, '*');
}
void display(char c)
{
display(1, c);
}
void display()
{
display(1, '*');
}
The down side here is your repeating the default values. That makes this brittle as a change of the default values requires you to change it in multiple places.