Swapping two integers without a temp variable
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!]
[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; \
} \
___________________________________
bishop_pass, it would be even better to write the macro as:
since your version will cause a syntactic error if you write something like:
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) \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
#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
#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
Popular Topics
Advertisement