SemtexB
SemtexB

Reputation: 660

Default value in C++ depending on other input argument

It looks like something like this in the declaration is not possible:

void func(float a, int b=int(a+1)){/*do stuff*/}

Basically, I want the default value of b depending on a. Is there a proper workaround for this, besides overloading func?

Upvotes: 1

Views: 182

Answers (2)

user6464825
user6464825

Reputation:

You can implement what @tobi303 mentioned. But if you really want 2 separate variables, you can also implement the following:

void func(float a)
{
    int b = (int)a + 1;
    // Do stuff...
}

Overloading is also possible:

void func(float a, int b)
{
    // Do stuff...
}

void func(float a)
{
    func(a, (int)a + 1);
}

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409422

Overloading: One function taking only a as an argument, and it in turn call another function passing two arguments.

Something like

void func(float a, int b)
{
    // Do stuff...
}

void func(float a)
{
    func(a, static_cast<int>(a) + 1);
}

Upvotes: 5

Related Questions