1

I need to define a macro in C that does the following.

swap_m(t,x,y) interchanges the two arguments x, y of type t.

I'm not really sure how to set x and y to type t. It could be really simple, but I'm new to C and not really sure how to do this.

4

4 回答 4

4

尝试

#define SWAP(x, y, t) \
    do {
        t __temp = x;
        x = y;
        y = __temp;
    } while (0)

用于

int a = 1, b = 2;
SWAP(a, b, int);
于 2012-09-15T21:06:39.300 回答
0

您可以利用 memcpy 和 sizeof 运算符:

void __swap(void* a, void* b, size_t size)
{
    void* temp= malloc(size);
    memcpy(temp,a,size);
    memcpy(a,b,size);
    memcpy(b,temp,size);
    free(temp);
}

#define swap(a,b) __swap(&a,&b,sizeof(a))
于 2012-09-15T21:14:41.183 回答
0

您只需将类型传递为t,例如swap_m(int, x, y)

t然后你可以在你的宏中定义一个类型的变量:

#define swap_m(TYPE, X, Y)    do { TYPE ___tmp = X; X = Y; Y = ___tmp; } while(0)
于 2012-09-15T21:07:33.950 回答
0

#define SWAP(a,b) { __typeof__(a) temp; temp = a; a = b; b = temp; }

就像在: http: //publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp ?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Ftypeof_operator.htm

于 2012-09-15T23:29:39.133 回答