• ### Popular Now

• 13
• 18
• 19
• 27
• 10

#### Archived

This topic is now archived and is closed to further replies.

# Swapping two integers without a temp variable

This topic is 5979 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

how do you swap two integers without a temp variable in C?

a = a ^ b;
b = a ^ b;
a = a ^ b;

##### Share on other sites
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!]

##### Share on other sites
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; \} \

___________________________________

##### Share on other sites
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 )

##### Share on other sites
#define swapi(x,y) \if(1) { \  int temp; \  temp = x; \  x = y; \  y = temp; \} else

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

##### Share on other sites
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

##### Share on other sites
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!]

##### Share on other sites
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!]

##### Share on other sites
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