+ 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
2 Réponses
+ 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!
+ 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)