Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using particular default parameters for a func

Tags:

c++

If I am having the following function defination. On calling I wish pass values just for a and c and use the default value for b how will I call this function

void func(int a=5,int b=2, int c=3)
{
..........
.........
}
like image 687
Tilak Raj Singh Avatar asked Apr 14 '26 06:04

Tilak Raj Singh


2 Answers

C++ does not support the following kind of syntax:

func(1, , 2);

This means that only the right-most parameters that you omit can take default values.

If you want to be able to have default parameters in arbitrary combinations, you could consider using boost::optional:

#include <boost/optional.hpp>
#include <iostream>

typedef boost::optional<int> OptionalInt;
typedef boost::optional<int> Default;

void func(OptionalInt a, OptionalInt b, OptionalInt c)
{
   if (!a) a = 5;
   if (!b) b = 2;
   if (!c) c = 3;
   std::cout << *a << std::endl;
   std::cout << *b << std::endl;
   std::cout << *c << std::endl;
}

int main()
{
   func(1, Default(), 1);
}

Output:

1
2
1
like image 176
JBentley Avatar answered Apr 16 '26 20:04

JBentley


According to the C++ 11 standard (N3485): 8.3.6 [dcl.fct.default]

For non-template functions, default arguments can be added in later declarations of a function in the same scope. Examples from the standards:

void f(int, int)

void f(int, int = 7); //OK

So the rule is that you have to specify default arguments from the right to the left of the parameter list. You cannot only specify default value to a without specifying the b and c before that:

void func(int a = 10, int b, int c); //ERROR

However,you may try the following:

void func(int a,int b, int c=3); //set default for c at first
void func(int a,int b = 5, int c);  //at later declarations, set for b
void func(int a =10, int b, int c);//at even later declarations, set for a

With the above, you can call the function as follows:

func(20); //call use default value of b and c
func(15,20); //call use default value of c
func(10,20,30); //do not use default value
func(); // use default values for a, b and c

So you can use default values of b and c at the same time as you like, or use c only, but you cannot call func by using default value of b only since it is the middle of the parameter list, similarly, you cannot call func using default value of a only. This way, you only add declarations and do not have redundant code. However, you can not really call them such that they can use default values in arbitrary way.

You can find a live example here default arguments example

like image 37
taocp Avatar answered Apr 16 '26 22:04

taocp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!