How can I swap two values without using a temporary?
Submitted by: AdministratorThe standard hoary old assembly language programmer's trick is:
a ^= b;
b ^= a;
a ^= b;
But this sort of code has little place in modern, HLL programming. Temporary variables are essentially free, and the idiomatic code using three assignments, namely
int t = a;
a = b;
b = t;
is not only clearer to the human reader, it is more likely to be recognized by the compiler and turned into the most-efficient code (e.g. perhaps even using an EXCH instruction). The latter code is obviously also amenable to use with pointers and floating-point values, unlike the XOR trick.
Submitted by: Administrator
a ^= b;
b ^= a;
a ^= b;
But this sort of code has little place in modern, HLL programming. Temporary variables are essentially free, and the idiomatic code using three assignments, namely
int t = a;
a = b;
b = t;
is not only clearer to the human reader, it is more likely to be recognized by the compiler and turned into the most-efficient code (e.g. perhaps even using an EXCH instruction). The latter code is obviously also amenable to use with pointers and floating-point values, unlike the XOR trick.
Submitted by: Administrator
Read Online C Programming Job Interview Questions And Answers
Top C Programming Questions
☺ | Why does this code crash? |
☺ | What is wrong with this declaration? |
☺ | How can I read/write structures from/to data files? |
☺ | What does static variable mean in c? |
☺ | How can I increase the allowable number of simultaneously open files? |
Top Coding/Programming Categories
☺ | Python Interview Questions. |
☺ | OOP Interview Questions. |
☺ | Software engineering Interview Questions. |
☺ | PHP Interview Questions. |
☺ | VBA (Visual Basic for Applications) Interview Questions. |