×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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

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

Program 1:

#include <iostream>
using namespace std;

int sum(int X, int Y = 20, int Z = 30)
{
    return (X + Y + Z);
}

int main()
{
    int A = 0, B = 0;

    A = sum(5, 10);
    B = sum(10);

    cout << A << " " << B;

    return 0;
}

Output:

45 60

Explanation:

Here, we created a function sum(), here we use two default arguments Y and Z with values 20 and 30 respectively.

Default arguments mean, if we don’t pass any value for default argument then it takes default specified value.

In the main() function, we declared two variables A and B with initial value 0.

Here, we made two function calls:

1st function call:
    A = sum(5,10);
    Here, X=5 and Y=10 and Z took default value 30. 
    Then A will be 45 after the function call.

2nd function call:
	B = sum(10);
    Here X=10 and Y and Z took default values 20 and 30 respectively. 
    Then B will be 60 after the function call.

Program 2:

#include <iostream>
using namespace std;

int sum(int X = 10, int Y = 20, int Z)
{
    return (X + Y + Z);
}

int main()
{
    int A = 0, B = 0;

    A = sum(5, 10);
    B = sum(10);

    cout << A << " " << B;

    return 0;
}

Output:

main.cpp: In function ‘int sum(int, int, int)’:
main.cpp:4:5: error: default argument missing for parameter 3 of ‘int sum(int, int, int)’
 int sum(int X = 10, int Y = 20, int Z)
     ^~~

Explanation:

We can use only trailing argument as a default argument, that's why the above program will generate an error.

Program 3:

#include <iostream>
using namespace std;

int K = 10;

int sum(int X, int* P = &K)
{
    return (X + (*P));
}

int main()
{
    int A = 0, B = 20;

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

    A = sum(5, &B);
    cout << A << " ";

    return 0;
}

Output:

15 25

Explanation:

Here, we defined a function sum() with a pointer as a default argument that stores the address of global variable K as a default value.

Here we made two function calls.

1st function call:

A = sum(5);

In this function call, returns (5+10), here the value of *P will be 10. Because pointer P contains the address of global variable K.  Then it will return 15. 

2nd function call:

A = sum(5,&B);

In this function, we passed the address of B then return statement will be like this:

return (5+20)

Then the final values are 15 and 25 will print on the console screen.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.