Sign in to follow this  

swap pointers question

This topic is 2852 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

How is this not the same thing?? 1. #define SWAP(x0,x) {float * tmp=x0;x0=x;x=tmp;} and 2. void SWAP(float *a, float *b) { float *temp = a; a = b; b = temp; }

Share this post


Link to post
Share on other sites
1 is a macro, 2 is a function.

1 will actually swap the pointers, 2 won't because the pointers are passed by value.

Quick fix for 2, assuming C++:
void SWAP(float *& a, float *& b)

Also, C++ provides a swap function out of the box:
std::swap(a, b);

If that doesn't answer your question, be more specific.

Share this post


Link to post
Share on other sites
Quote:
Original post by alvaro
Also, notice that the macro version will always have problems with code like this:
  while (a<b) SWAP(a++,b--);


That's right! There's absolutely no reason to implement this as a macro. Only bad things will come of it! *scary sounds*

Share this post


Link to post
Share on other sites
haha tx for the help i will use the other option an use the std::swap()

Here is somthing wierd which gave me the worlds biggest headache right now. I am doing a project on stable fluids implemented with c++ and opengl. For my physics part i have a lot of for loops in the solver function and i just could not get my whole program to work. So now i have been sitting with this for 3 straight days and trying to make my code look exactly like the reference i am using.

Here comes the wierd part. The reason i mentioned for loops is that to solve my problem i had to write instead of another loop like this:

for(int i=1; i <= *N; i++){for(int j=1; i <= *N; i++){

I wrote instead:

#define FOR_EACH_CELL for ( i=1 ; i<=*N ; i++ ) { for ( j=1 ; j<=*N ; j++ ) {
#define END_FOR }}

AND IT WORKED!!!!

Now I am wondering WHY?

Share this post


Link to post
Share on other sites
Quote:
Original post by tompish
for(int i=1; i <= *N; i++){for(int j=1; i <= *N; i++){

I wrote instead:

#define FOR_EACH_CELL for ( i=1 ; i<=*N ; i++ ) { for ( j=1 ; j<=*N ; j++ ) {
#define END_FOR }}

AND IT WORKED!!!!

Now I am wondering WHY?

Look carefully and you'll see why. Hint: it has nothing to do with the fact that you're using a macro. ;)

Oh, in C++, arrays start at index 0, just in case you didn't know.

Share this post


Link to post
Share on other sites

This topic is 2852 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this