0

Why value of b is not swapping

Swap function

19th Aug 2021, 6:04 AM
Viraj
Viraj - avatar
7 Antworten
+ 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;
19th Aug 2021, 6:21 AM
TOLUENE
TOLUENE - avatar
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
19th Aug 2021, 6:04 AM
Viraj
Viraj - avatar
0
Sayed thanks bhai ❤️
19th Aug 2021, 6:22 AM
Viraj
Viraj - avatar
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
19th Aug 2021, 6:57 AM
Viraj
Viraj - avatar
- 1
Jay Matthews I know that bro But why my code is giving garbage value for b/y ??
19th Aug 2021, 6:12 AM
Viraj
Viraj - avatar
- 1
Jay Matthews I have given my code see above 👆☝️
19th Aug 2021, 6:16 AM
Viraj
Viraj - avatar
- 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().
19th Aug 2021, 6:53 AM
Ipang