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()
?
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.
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.
Default arguments are useful in situations where some arguments always have the same value.
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).
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With