Jump to content
  • Advertisement

Archived

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

onlinegmz

Swapping two integers without a temp variable

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

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement
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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!