2

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;
} 
Marcus Moo
  • 196
  • 1
  • 2
  • 20

3 Answers3

3

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).

iosdude
  • 1,131
  • 10
  • 27
1

They will assume by default that y will be 2, thus when you fill in int x, it'll automatically take in (x,2).

0

In your declaration for mysteryFunction you give a default value of 2 to the second argument. Then you call it with only 1 argument so the default gets used for the second argument. So y=20 and 20 * 2 = 40. Don't mix up variable names. The x and y in main have nothing to do with x and y in mysteryFunction

MotKohn
  • 3,485
  • 1
  • 24
  • 41