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 A = 10;
int& fun()
{
return A;
}
int main()
{
fun() = 20;
cout << A;
return 0;
}
Program 2:
#include <iostream>
using namespace std;
void fun(int& X, int& Y)
{
X = X - EOF - NULL;
Y = Y - (-EOF) + NULL;
}
int main()
{
int A = 10;
int B = 20;
fun(A, B);
cout << A << " " << B;
return 0;
}
Answer Program 1:
Output:
Explanation:
In the above program, we created a global variable A with initial value 10. In C++, the function that returns a reference of a variable, that can be used as an LVALUE. So that here we can set a value into the global variable.
Here, we set the value 20 into global variable A using function fun().
Answer Program 2:
Output:
Explanation:
Here we declared two variables A and B with initial values 10 and 20 respectively. And, we created function fun() that takes an argument as a reference. So, that changes done in the reference variable will be reflected in A and B.
Now, evaluate the expressions,
X = X - EOF - NULL; Y = Y - (-EOF) + NULL; Expression 1: X = 10 - -1 - 0 X = 10 + 1 -0 X = 11 Expression 2: Y = Y - (-EOF) + NULL Y = 20 – (- -1) + 0 Y = 20 – 1 + 0 Y = 19
Then the final result will be: 11 19
need an explanation for this answer? contact us directly to get an explanation for this answer