Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C macro templace abuse

Name: Anonymous 2012-06-14 1:13

#include <stdio.h>
#define swap(T,x,y) ({T tmp = (x); (x) = (y); (y) = tmp;})

int main() {
    int x = 2, y = 5;

    swap(int, x, y);
    printf("x = %d, y = %d", x, y); //x = 5, y = 2
    return 0;
}


Is this bad practice?

Name: Anonymous 2012-06-14 1:45

>>2
lol

>>1
Personally, I'd just write a generic function, since it will work with arrays and structs as well (and I guess I just prefer using functions over macros). Aside from that, I don't think there's anything largely wrong with what you're doing.

#include <stdio.h>

static void *swap(void *v1, void *v2, size_t size)
{
    char *a = v1;
    char *b = v2;

    while (size--) {
        char tmp = *a;

        *a++ = *b;
        *b++ = tmp;
    }
    return v1;
}

int main(void)
{
    int x = 2;
    int y = 5;

    swap(&x, &y, sizeof x);
    printf("x = %d, y = %d\n", x, y);
    return 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List