Not sure whether to put this in the C++ forum or here. But I seem to remember one time being very impressed when I read somewhere of a slick way to swap 2 variables without the use of a temporary var. I wanted to use this in a bubble sort I am writing for a class in Java. Here is the dumb obvious way you swap 2 vars:
temp = n1;
n1 = n2;
n2 = temp;
Now, I looked this idea up on the internet and found this
a = a+b;
b = a-b;
a = a-b;
This does switch 2 vars without an intermediary, which is cool, but I remember something really short and sweet. I can do this in one line (definitely want it all on one line), but it looks pretty gross:
a=(a-(b=(a=a+b)-b));
or as I discovered I needed to do because of order of operations:
a = -((b=(a=a+b)-b)-a);
and here's how it looks in my bubble sort:
n=-((n[i+1]=(n+=n[i+1])-n[i+1])-n);
Like I said, pretty gross (and just try to figure it out!). So I wonder if anyone knows what I am thinking of. By the way, here's something else I came up with, but it still doesn't excite me:
n = n[i+1] + (n[i+1]=n)*0;
It seems to work, but its kind of scary since once again it is very dependent on in what order the statement is evaluated.
temp = n1;
n1 = n2;
n2 = temp;
Now, I looked this idea up on the internet and found this
a = a+b;
b = a-b;
a = a-b;
This does switch 2 vars without an intermediary, which is cool, but I remember something really short and sweet. I can do this in one line (definitely want it all on one line), but it looks pretty gross:
a=(a-(b=(a=a+b)-b));
or as I discovered I needed to do because of order of operations:
a = -((b=(a=a+b)-b)-a);
and here's how it looks in my bubble sort:
n=-((n[i+1]=(n+=n[i+1])-n[i+1])-n);
Like I said, pretty gross (and just try to figure it out!). So I wonder if anyone knows what I am thinking of. By the way, here's something else I came up with, but it still doesn't excite me:
n = n[i+1] + (n[i+1]=n)*0;
It seems to work, but its kind of scary since once again it is very dependent on in what order the statement is evaluated.