Vinod
Vinod

Reputation: 1

How to select default arguments that are passed to a function

I have a program here: I have a doubt in passing arguments to the function display().

void display(int = 20,int = 30,int = 50);

int main()
{
    display(5,12);
    return 0;
}

void display(int i,int j,int k)
{
    cout<<i<<endl;
    cout<<j<<endl;
    cout<<k<<endl;
}

If this function display is called by passing 2 arguments to it, how can we make sure that these arguments are treated as first and third, whereas second argument is default.

Upvotes: 0

Views: 209

Answers (3)

John Dibling
John Dibling

Reputation: 101456

As others have said, you can't intermix defaulted parameters between non-defaulted parameters. One way to get similar behavior is to use a structure to pass in parameters, and only set the values you need. A la:

#include <cstdlib>
#include <iostream>
using namespace std;

struct FnParams
{
    int i, j, k;
    FnParams() : i(20), j(30), k(40)  {};
};

void DoTheThing(FnParams params = FnParams())
{
    cout << params.i << endl;
    cout << params.j << endl;
    cout << params.k << endl;
}

int main()
{
    DoTheThing();

    FnParams p;
    p.j = 42;
    DoTheThing(p);

    return 0;
}

There are not many functions that benefit from this kind of construct. But those that do tend to grow continiously over time, with new parameters being added, old ones being deleted, etc. The method above has the added benefit of making it easier to change the parameters passed to the function while not necessitating you touching 1000's of places in the code that call your function every time you make one small change.

Upvotes: 2

slebetman
slebetman

Reputation: 113866

You can't. The default argument is ALWAYS at the end.

The best that you can do is something like the following pattern:

// Choose a number that is NEVER valid as input to represent default:
#define DEFAULT_VAL 0x7fffffff

void display (int i, int j, int k)
{
    if (i == DEFAULT_VAL) i = 20;
    if (j == DEFAULT_VAL) i = 30;
    if (k == DEFAULT_VAL) i = 50;

    cout<<i<<endl;
    cout<<j<<endl;
    cout<<k<<endl;
}

Hold on, I just realised that this is C++. In which case you can use function overloading to simulate what you want:

void display (int i, int j, int k)
{        
    cout<<i<<endl;
    cout<<j<<endl;
    cout<<k<<endl;
}

void display (int i, int k)
{        
    cout<<i<<endl;
    cout<<30<<endl;
    cout<<k<<endl;
}

Well, both has pros and cons. Depends on what you really want to do.

Upvotes: 3

j_random_hacker
j_random_hacker

Reputation: 51226

You can't, unfortunately. Only trailing parameters can use default parameters in C++.

If this is a problem, you could either:

  • Reorder the parameters
  • Write another overload of the function.

Upvotes: 2

Related Questions