3 AnswersNew Answer
You will have to return the value of x in your swap function... and call the function like this: x = swap(x, y);
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
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.