C++ allows a function to assign an argument a default value when no argument is specified in a call to that function. The third argument of following function will have “0” when it is not passed by the caller.
int sum(int num1, int num2, int num3 = 0)
{
return num1 + num2 + num3;
}
When a method is called, all the arguments are pushed on stack and method pops them from stack and copy values in the formal arguments.
Let’s see the dis-assembly code generated for a method call with all the arguments:
sum (1,2,3);
// Here is the dis-assembly code for passing arguments to sum method
push 3 //push value 3 on stack
push 2 //push value 2 on stack
push 1 //push value 1 on stack
call sum (41123Fh) // call sum method
Here, we can see that all the three values are pushed on the stack.
Now see the dis-assembly code generated for a method call when no value to supplied for last argument:
sum(1,2);
// Here is the dis-assembly code for passing arguments to sum method
push 0 //Here 0 as default value for last argument
push 2 //push value 2 on stack
push 1 //push value 1 on stack
call sum (41123Fh) // call sum method
We can see that “push 0” assembly code is pushing “0” (specified in method’s definition) as default value for last argument “num3”.