开发者

Which default argument is evaluated first and why?

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

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

int funt2()
{
    cout<<"funt2 called"开发者_StackOverflow社区<<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()?


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


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());
}


The language does not require any particular order. The order used will be compiler dependent.


Compiler specific and from there it goes down to the CPU. CPU might branch that call into separate branches, it might try to do some predictions, or if the CPU thinks func1 is way faster than func2 it will run func1 and a bunch of other operations before func2 so it optimizes.


As C++ standard doesn't define the order so it's depend on compiler.

You can simply try a few popular c++ compilers: GCC, VS2008/VS2010 etc. Then you will see totally different result.


compiler dependent. it maybe funt1 then funt2 then funt3 or any other combination.


As noted by everybody else, the order of evaluation of function parameters is unspecified by the C++ standard. This allows each compiler to choose an optimal order, whether that order is determined by convenience or efficiency.

You may even find that the order can change based on the optimization flags you give to your compiler.

In order to guarantee the sequence of the function calls you need to introduce a sequence point between the calls. I accomplish this below by creating two different versions of the function, so that only one function call is made as a parameter.

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

void funt3()
{
    int x = funt1();
    funt3(x);
}


It is because the parameters of funt3(sp?) needs to work out x then y. i.e. funt1() then funt2() before considering the contents of funt3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜