Swapping two numbers, what is the mistake in the code the numbers are not swaped?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Swapping two numbers, what is the mistake in the code the numbers are not swaped??

#include<iostream> using namespace std; void swap(int,int); int main( ) { int a,b; cout"enter the values of a and b"<<endl; cin>>a>>b; swap(a,b); cout<<"swap values of a and b are"; cout<<a<<b; } void swap(int x,int y) { int temp; temp=x; x=y; y= temp; }

17th Nov 2018, 3:56 PM
Amit Vishwakarma
Amit Vishwakarma - avatar
7 Answers
+ 9
Hi Amit Vishwakarma , Your mistake in the method argument. You must take a pointer to integer not a local variable. void swap(int * x, int * y){ int temp; temp = *x; *x = *y; *y = temp; return; } and when you call the method you must put the address opterator & As: sawp(&a, &b); hope this help you..
17th Nov 2018, 4:13 PM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 6
without using pointers, the local variable inside the function is changed, but the actual value of the a and b( in your case) don't change.
17th Nov 2018, 4:35 PM
Shruti
Shruti - avatar
+ 5
You can just write 'int &' instead of 'int' in your declaration and definition of swap, then it works.
17th Nov 2018, 4:59 PM
HonFu
HonFu - avatar
+ 4
Because methods store local variables in the stack as a copy and when it finish the values will be released from memory. But when you use pointer the method will store the value in the dynamic memory by using their address.
17th Nov 2018, 4:35 PM
Mohammad Dakdouk
Mohammad Dakdouk - avatar
+ 2
But why can't we do without using pointer
17th Nov 2018, 4:24 PM
Amit Vishwakarma
Amit Vishwakarma - avatar
+ 1
without using poiters you are passing the argument by value. But what is needed is their reference.
17th Nov 2018, 4:33 PM
Ulisses Cruz
Ulisses Cruz - avatar
- 1
I update the code check it.
17th Nov 2018, 4:19 PM
Mohammad Dakdouk
Mohammad Dakdouk - avatar