Swapping two integers without a temp variable

Started by
24 comments, last by onlinegmz 22 years, 5 months ago
how do you swap two integers without a temp variable in C?
Advertisement
a = a ^ b;
b = a ^ b;
a = a ^ b;
ReactOS - an Open-source operating system compatible with Windows NT apps and drivers
You''ll want to use a temporary variable if you''re looking for speed. Martee is correct though.

[Resist Windows XP''s Invasive Production Activation Technology!]
Are you trying to make a C macro that does it? You can still do it and use a temp var.


#define swapi(x,y) { \
int temp; \
temp = x; \
x = y; \
y = temp; \
} \


___________________________________

_______________________________
"To understand the horse you'll find that you're going to be working on yourself. The horse will give you the answers and he will question you to see if you are sure or not."
- Ray Hunt, in Think Harmony With Horses
ALU - SHRDLU - WORDNET - CYC - SWALE - AM - CD - J.M. - K.S. | CAA - BCHA - AQHA - APHA - R.H. - T.D. | 395 - SPS - GORDIE - SCMA - R.M. - G.R. - V.C. - C.F.
bishop_pass, it would be even better to write the macro as:
#define swapi(x,y) \do { \   int temp; \   temp = x; \   x = y; \   y = temp; \} while (0)


since your version will cause a syntactic error if you write something like:

if (some_condition)   swap(x,y);else   whatever();

The semi-colon after swap wouldn''t be allowed unless you have the do-while wrapper.
(I know, I''m being picky )
#define swapi(x,y) \if(1) { \  int temp; \  temp = x; \  x = y; \  y = temp; \} else 


[Resist Windows XP''s Invasive Production Activation Technology!]
or just

#define swapi(x,y) \
{ \
int temp; \
temp = x; \
x = y; \
y = temp; \
}

seems dumb to put useless do while cases or if statements is you just want to preserve scope.

and, of course, an inline function is preferable to all of the above.

--michael
quote:Original post by chiuyan
seems dumb to put useless do while cases or if statements is you just want to preserve scope.

That''s not what he was talking about. He was talking about it having a syntax error due to the else after the macro''s use being left without an if.

[Resist Windows XP''s Invasive Production Activation Technology!]
quote:Original post by chiuyan
and, of course, an inline function is preferable to all of the above.

Inline functions are even part of C now .

[Resist Windows XP''s Invasive Production Activation Technology!]
Or using asm:

#define swap(a,b) \
\__asm
\{
\ mov eax, a
\ mov ebx, b
\ mov a, ebx
\ mov b, eax
\}

Which is probably what the compiler would do with your inline function anyway

This topic is closed to new replies.

Advertisement