Salman Khan
Salman Khan

Reputation: 11

Passing a single argument to a multi argument function

I have a variable let say int c in a given function. I want to pass it to the other class.let say it is

function(int a, int b, int c);

I want only to pass the third argument while ignore the first two.

i.e. : I just want to pass int c, as function (c) and it just pass it to the third argument. I don't want to pass it like function(0,0,c); .. Is there any possibility. Please advise.

Upvotes: 1

Views: 102

Answers (4)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33944

You can have default values for your function:

void function(int c, int a = 0, int b = 0);

or you can overload your function:

void function(int a, int b, int c) {
    //implementation 1
}

void function(int c) {
    function(0, 0, c);
}

You could in both cases use it like this:

function(c);

Note : when we use default values, in function definition the argument with default values must be the last in order for example :

void function(int a = 0, int b = 0, int c)

is not a valid format.

Upvotes: 2

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 123228

Imho already with three parameters it is worth to structure them

struct foo { 
    int a;
    int b;
    int c;
};

allowing to have a nicer function interface

void function(foo f);

How does this help? You can provide a default constructor and let the user set only those fields that are not default:

struct foo {
    int a;
    int b;
    int c;
    foo() : a(0),b(0),c(0) {}
};

foo f;
f.b = 12;
f.c = 32;
function(f);

Now any combination of default / non-defaults is possible.

One could argue that the struct isnt really necessary and the problem is just shifted to the constructor of foo or the need to correctly set the members, but I think this is a valid approach that was missing from the other answers. (btw I am not claiming that my example here demonstrates best pratice, but the details would matter on the exact use case)

Upvotes: 0

R Sahu
R Sahu

Reputation: 206717

When you have the situation where function(c) is equivalent to function(0, 0, c), it sounds like a poor design. Normally, you can use default argument values for the parameters starting from the end. It would make sense if function(c) were equivalent to function(c, 0, 0).

You can accomplish that easily by declaring the function as:

void function(int c, int a = 0, int b = 0);

I realize that you can accomplish your goal by overloading function as:

void function(int c)
{
   function(0, 0, c);
}

but it still appears to be a poor interface to me.

Upvotes: 0

Vinayak Garg
Vinayak Garg

Reputation: 6616

Looks like you want to do function overloading. Something like this-

function(int a, int b, int c);

function(int c);

inside second function you can call first function with appropriate values for a and b

Upvotes: 2

Related Questions