i know how to swap 2 variables in c++ . ie you use std::swap(a,b).
question:
does the c standard library have a similar function to c++ std::swap() or do i have to define it myself
i know how to swap 2 variables in c++ . ie you use std::swap(a,b).
question:
does the c standard library have a similar function to c++ std::swap() or do i have to define it myself
Yes you need to define it yourself.
void swap(void* a, void* b, size_t length)
, but unlike std::swap
, it's not type-safe.inline
keyword).We could also define a macro like
#define SWAP(a,b,type) {type ttttttttt=a;a=b;b=ttttttttt;}
but it shadows the ttttttttt
variable, and you need to repeat the type of a
. (In gcc there's typeof(a)
to solve this, but you still cannot SWAP(ttttttttt,anything_else);
.)
And writing a swap in place isn't that difficult either — it's just 3 simple lines of code!
There is no equivalent in C - in fact there can't be, as C doesn't have template functions. You will have to write separate functions for all the types you want to swap.
You can do something similar with a macro if you don't mind using a gcc extension to the C language, typeof
:
#include <stdio.h>
#define SWAP(a, b) do { typeof(a) temp = a; a = b; b = temp; } while (0)
int main(void)
{
int a = 4, b = 5;
float x = 4.0f, y = 5.0f;
char *p1 = "Hello";
char *p2 = "World";
SWAP(a, b); // swap two ints, a and b
SWAP(x, y); // swap two floats, x and y
SWAP(p1, p2); // swap two char * pointers, p1 and p2
printf("a = %d, b = %d\n", a, b);
printf("x = %g, y = %g\n", x, y);
printf("p1 = %s, p2 = %s\n", p1, p2);
return 0;
}
Another macro not already mentioned here: You don't need to give the type if you give the temporary variable instead. Additionally the comma operator is useful here to avoid the do-while(0) trick. But usually I don't care and simply write the three commands. On the other hand a temporary macro is useful if a and b are more complex.
#define SWAP(a,b,t) ((t)=(a), (a)=(b), (b)=(t))
void mix_the_array (....)
{
int tmp;
.....
SWAP(pointer->array[counter+17], pointer->array[counter+20], tmp);
.....
}
#undef SWAP
Check your compiler documentation. The compiler may have a swapb
function for swapping bytes and my provide other similar functions.
Worst case, waste a day and write some generic swap functions. It won't consume a significant amount of your project's schedule.