I do not understand why mysteryfunction(y) will equate to 40 when i int mysteryFunction(int, int =2). Anyone can explain to me?
Best, MM
#include <iostream>
using namespace std;
int mysteryFunction (int, int = 2);
int main()
{
int x = 10, y = 20;
cout << mysteryFunction (y);
}
int mysteryFunction (int x, int y)
{
return x * y;
}
In the declaration ofmysteryFunction()
the second parameter is assigned a default value of 2
, so if you call it only with one argument the second argument y
will be 2
.
Hence doing mysteryFunction(20)
is basically the same as doing mysteryFunction(20, 2)
, which according to your code should return 20 * 2 = 40.
You may have been confused by the fact that the variable you pass to mysteryFunction()
as its first argument is named y
, same as the second parameter in its definition. However, those are completely different variables. In fact, it doesn't matter how you call them, only the position of arguments/parameters matters (along with their type if you take function overloading into account).