void swap(int& a, int& b ) {
a^=b^=a^=b; }
You cannot swap two numbers using call by value, because the called function does not have access to the original copy of the numbers.Swap with call by reference... This routine uses exclusive or swap without temporary variable.void swap (int *a, int *b) {*a ^= *b;*b ^= *a;*a ^= *b;return;}
The using of term 'call-by-reference' implies function-call, so please rethink your question...
In call by reference, you are calling the program by passing the variables address(reference) to it. This is done through the use of functions. Any changes made in the variables to the function will be reflected even the calling function.Here is a code snippet for swapping two numbers.#includevoid swap( int *a, int *b){int temp = *a;*a = *b;*b = temp;}int main(){int a=8, b=9;printf("The value of a and b before swap = %d %d\n", a, b);swap(a,b);printf("The value of a and b after swap = %d %d\n", a, b);return 0;}
void swap(int &x, int &y) { x ^= y ^= x; } - or - void swap(int &x, int &y) { int t = x; x = y; y = t; }
// Note: ^ is the XOR operator a = a ^ b b = b ^ a a = a ^ b
The concept of being able to swap numbers in an addition sum is called the commutative property of addition.
You cannot do that in C, but you can pass pointers to objects, like this: void swap (int *a, int *b) { int tmp=*a; *a=*b; *b= tmp; } int x=3, y=4; swap (&x, &y);
bubble_sort (int N, int *A) { int i; swap = 1; while (swap) { swap = 0; for (i=0; i<N-1; ++i) { if (A[i] > A[i+1]) { swap = 1; A[i] ^= A[i+1]; A[i+1] ^= A[i]; A[i] ^= A[i+1]; } } } }
call them
You have to pass the address of the variables.void swap (int *pa, int *pb){...}
swap (int *a, int *b) { *a ^= *b; *b ^= *a; *a ^= *b; } int c = 13; int d = 27; swap (&c, &d); /*c is now 27 and d is now 13 */ Note: there is no call-by-reference in C. In C++: void swap (int &a, int &b) { . int tmp; . tmp = a; . a = b; . b = tmp; }
Q. what is calling by reference? How it is different from call by value? Write a C function to swap two given numbers using call by reference mechanism.Ans.When an argument is passed by reference, the caller actually allows the called function to modify the original variable's value.Sends the address of a variable to the called function.Use the address operator(&) in the parameter of the called function.Anytime we refer to the parameter, therefore we actually referring to the original variable.If the data is manipulated and changed in the called function, the original data in the function are changed./*swap function to interchange values by call by reference*/#include#includevoid swaping(int *x, int *y);int main(){int n1,n2;printf("Enter first number (n1) : ");scanf("%d",&n1);printf("Enter second number (n2) : ");scanf("%d",&n2);printf("\nBefore swapping values:");printf("\n\tn1=%d \n\tn2=%d",n1,n2);swaping(&n1,&n2);printf("\nAfter swapping values:");printf("\n\tn1=%d \n\tn2=%d",n1,n2);getch();return 0;}void swaping(int *x, int *y){int z;z=*x;*x=*y;*y=z;}