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

This section contains the C++ find output programs with their explanations on C++ Reference Variable (set 2).
Submitted by Nidhi, on June 09, 2020

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;
}

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.

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;
}

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.