What will be the output of the following C++ code? [code] #include <iostream> using namespace std; void swap(int &a, int &b);

What will be the output of the following C++ code?
Code:
    #include <iostream>
    using namespace std;
    void swap(int &a, int &b);
    int main()
    {
        int a = 5, b = 10;
        swap(a, b);
        cout << "In main " << a << b;
        return 0;
    }
    void swap(int &#038;a, int &#038;b)
    {
        int temp;
        temp = a;
        a = b;
        b = temp;
        cout << "In swap " << a << b;
    }
A. In swap 105 In main 105
B. In swap 105 In main 510
C. In swap 510 In main 105
D. In swap 510 In main 510
 
Answer: a
Explanation: As the function is called by reference i.e. all the changes are done directly into the memories of a and b. Therefore changes made to a and b in swap function is reflected back to main function. Hence the values of a and b in swap as well as in main function is changed.
Output:
Code:
$ g++ ref.cpp
$ a.out
In swap 105 In main 105
 

Tìm kiếm

Back
Top