Explain output of this simple swapping number program? 🤔 why output is x=6? | SoloLearn: Learn to code for FREE!

+2

Explain output of this simple swapping number program? 🤔 why output is x=6?

#include <iostream> using namespace std; void swap(int x, int y) { x = y; } int main() { int x = 6; int y = 9; swap(x,y); cout<<x; return 0; } // output x=6

c++

5/30/2020 7:31:25 AM

Tushar Vasave

3 Answers

New Answer

+4

You will have to return the value of x in your swap function... and call the function like this: x = swap(x, y);

+4

In c++ u can pass argument to the function in 2 ways. 1.pass by value 2. Pass by reference In pass by value, the parameters are passed in a copied manner. Like ur program swap(int x,int y) the x and y value of main function 6 and 9 copied to x and y parameters of swap function. Then the swap function would do it's internal operations and x and y's copied value dissappears. Then while coming back to main function it has only value of x = 6; it prints 6. In pass by reference the address of the variables are passed instead of values. For instance if u make ur function swap(int &x, int &y) the address of x and y will be passed to swap function. And whatever the operation done on that variable will be reflected in main method. Because address is same throughout the program for that variables. Use swap(int &x, int &y). U will get desired output as 9

+3

In C++, when you pass arguments to a function, they are copied to the parameters. Changing the copy within the function has no effect on the original variables.