+ 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

30th May 2020, 7:31 AM
Tushar Vasave
Tushar Vasave - avatar
3 odpowiedzi
+ 4
You will have to return the value of x in your swap function... and call the function like this: x = swap(x, y);
30th May 2020, 7:36 AM
Namit Jain
Namit Jain - avatar
+ 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
1st Jun 2020, 3:55 AM
Marana Coder
Marana Coder - avatar
+ 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.
30th May 2020, 7:42 AM
HonFu
HonFu - avatar