Whats the difference between
and...Code:void swap(int* a,int* b) { int x=*a,y=*b; x=x+y; y=x-y; x=x-y; *a=x; *b=y; return; }
Code:void swap(int* a,int* b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; return; }
This is a discussion on Puzzling pointers... within the C Programming forums, part of the General Programming Boards category; Whats the difference between Code: void swap(int* a,int* b) { int x=*a,y=*b; x=x+y; y=x-y; x=x-y; *a=x; *b=y; return; } and... ...
Whats the difference between
and...Code:void swap(int* a,int* b) { int x=*a,y=*b; x=x+y; y=x-y; x=x-y; *a=x; *b=y; return; }
Code:void swap(int* a,int* b) { *a=*a+*b; *b=*a-*b; *a=*a-*b; return; }
Functionally, they both have the same net effect (presumably to perform a swap in a rather roundabout way, assuming no arithmetic overflow). The first version simulates call by copy-restore (a.k.a. value-result), the second just uses pointer arguments to simulate call by reference, as is the usual method in C.Whats the difference between
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
Does it matter?
They're both broken attempts to swap two integers.
The first fails miserably in attempting to avoid creating one temporary, by instead creating two temporaries.
Try calling the second one with swap(&a,&a)
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.
Oh yes, but that means that I am wrong to say that they have the same net effect. Call by copy-restore avoids this problem.Try calling the second one with swap(&a,&a)
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
I implemented the second in my code and it didn't work...
I replaced it with first and it works fine....
A quick test shows that it works, with the caveat pointed out by Salem.I implemented the second in my code and it didn't work...
I hope that you are actually implementing swap() for your actual code with the more straightforward implementation.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
How about just
It does exactly what you think it should do, has no unexpected side effects, and doesn't rely on the overflow behaviour of your machine.Code:int temp = *a; *a = *b; *b = temp;
Oh, and stop paying attention to dumb programming tricks.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
I support http://www.ukip.org/ as the first necessary step to a free Europe.