Q:

C++ Default Argument | Find output programs | Set 2

belongs to collection: C++ find output programs

0

This section contains the C++ find output programs with their explanations on C++ Reference Variable (set 2).

Program 1:

#include <iostream>
using namespace std;

int K = 10;

int fun()
{
    return K;
}
int sum(int X, int Y = fun())
{
    return (X + Y);
}

int main()
{
    int A = 0;

    A = sum(5);
    cout << A << " ";

    K = 20;
    A = sum(5);
    cout << A << " ";

    return 0;
}

Program 2:

#include <iostream>
#define NUM 10 + 20
using namespace std;

int fun(int X = NUM)
{
    return (NUM * NUM);
}

int main()
{
    int RES = 0;

    RES = fun();

    cout << RES;

    return 0;
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

Output:

15 25

Explanation:

Here, we defined two functions fun() and sum().

The fun() function returns the value of global variable K. and function sum() take the second argument as a default argument, here we use fun() as a default value of the Y. If we modify the value of global variable K, then the default value will be changed automatically. 

Now come to the function calls,

1st function call:

A = sum(5);

Here, X = 5 and Y =10, because the value of K is 10 till now. then function return 15. 

2nd function call:

A = sum(5);

Before the second function call, we modify the value of the global variable K. The new value of K is 20. Then X = 5 and Y =20. Then function sum() return 25.

Then the final output "15 25" will be printed on the console screen.

Answer Program 2:

Output:

230

Explanation:

Here, we defined function fun() that takes macro NUM as a default value of the argument.

Now, evaluate the expression used in the return statement,

NUM*NUM
10+20*10+20
10+200+20
230

Then function fun() will return 230, and that will be printed on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ find output programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C++ Arrays | Find output programs | Set 1... >>
<< C++ Default Argument | Find output programs | Set ...