Pls explain this function,void swap(int a,int b){ int t; t=a; a=b; b=t;} | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 1

Pls explain this function,void swap(int a,int b){ int t; t=a; a=b; b=t;}

This function is in call by value

22nd Apr 2017, 7:55 AM
Goudham Ram
Goudham Ram - avatar
2 Antworten
+ 3
It swaps the values of variables a and b. Initially you use a dummy variable t to help u swao the values. Assume a=1 and b=2 So now u assign t=a so t=1, Then you assign a=b so now a=2 Finally you assign b=t so now b=1 And viola you just swapped values of the variables a and b!
22nd Apr 2017, 8:11 AM
Shraddha
Shraddha - avatar
+ 3
It swaps a and b inside the function, but as it's call by value the actual a and b you used to call the function won't change (so this function has no effect at all on your main program). If you want to use it to swap the values of two variable you can do it with call by reference: void swap(int *a,int *b){ int t; t=*a; *a=*b; *b=t; } You call it like this: int a, b; swap(&a, &b); Or you make it a macro: #define swap(a,b) {int t; t=(a); (a)=(b); (b)=t;} or, without t: #define swap(a,b) {(a) = (a) + (b); (b) = (a) - (b); (a) = (a) - (b);} You call it like this: int a, b; swap(a,b)
22nd Apr 2017, 8:25 AM
Robobrine
Robobrine - avatar