0
Why value of b is not swapping
Swap function
7 ответов
+ 7
Guru patel
in your code
int temp;
x = temp ; //for this value of y is garbage as you didn't set the value of temp variable. Replace this with temp = x;
0
#include<iostream>
using namespace std;
void swap (int , int );
int main()
{
int a =5;
int b =6;
cout<<"before swapping value of a is :"<<a<<endl;
cout<<"before swapping value of b is :"<<b<<endl;
swap (a,b);
return 0;
}
void swap(int x, int y)
{ int temp;
x=temp;
x=y;
y=temp;
cout<<"value of a inside swap function is :"<<x<<endl;
cout<<"value of b inside swap function is :"<<y<<endl;
}
This is the code
0
Sayed thanks bhai ❤️
0
Ipang yeah bro I know it's 2nd method I was doing it by call by value method 😀 I mean without using any reference varibles
- 1
Jay Matthews I know that bro
But why my code is giving garbage value for b/y ??
- 1
Jay Matthews I have given my code see above 👆☝️
- 1
Your swap() function declaration should've been like
void swap( int&, int& );
And its definition should be
void swap( int& x, int& y )
{
int temp { x };
x = y;
y = temp;
}
This way changes to <x> and <y> in swap() will reflect in actual <a> and <b> variables in function main().