Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which default argument is evaluated first and why?

Tags:

c++

I have three functions, funt1(), funt2(), and funt3().

int funt1()
{
    cout<<"funt1 called"<<endl;
    return 10;
}

int funt2()
{
    cout<<"funt2 called"<<endl;
    return 20;
}

void funt3(int x=funt1(), int y=funt2())
{
    cout << x << y << endl;
}

My main function:

int main()
{
    funt3();
    return 0;
}

When I am calling funt3() in my main() method, why is funt1() is called first, and then funt2()?

like image 778
teacher Avatar asked Aug 30 '11 21:08

teacher


People also ask

What is default argument give its precedence?

A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

What are the default argument What is their use give example?

A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. The values passed in the default arguments are not constant. These values can be overwritten if the value is passed to the function.

In which situation default arguments are useful?

Default arguments are useful in situations where some arguments always have the same value.

What is a default argument how do you define one?

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).


2 Answers

It depends on your compiler. Others may call funct2() first. Neither C or C++ guarantee the order of evaluation of function arguments.

See Parameter evaluation order before a function calling in C

like image 59
Andrew Stein Avatar answered Oct 14 '22 05:10

Andrew Stein


C++ standard does not define that, so it's totally compiler-specific. That said, you should never rely on an instance of undefined behaviour.

EDIT: if you really want to keep functions invocations as default parameters to reduce the numbers of parameters you have to pass each time I suggest you do the following:

void funt3(int x, int y)
{
    cout<<x<<y<<endl;
}

void funt3(int x)
{
    funt3(x, funt2());
}

void funt3()
{
    funt3(funt1());
}
like image 40
gwiazdorrr Avatar answered Oct 14 '22 04:10

gwiazdorrr