定义一个预处理宏交换(T,X,Y) [英] Define a preprocessor macro swap(t, x, y)

查看:75
本文介绍了定义一个预处理宏交换(T,X,Y)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个预处理程序宏swap(t,x,y),它将在C/C ++中交换给定类型t的两个参数x和y. >

I need to define a preprocessor macro swap(t, x, y) that will swap two arguments x and y of a given type t in C/C++.Can anyone have any opinion on how can i do it?

推荐答案

如果要交换int或char等基本类型(实现XOR运算符),则可以使用三倍XOR技巧来交换值,而无需另一个变量:

If you want to swap basic types like int or char (which implement the XOR operator) you can use the tripple XOR trick to swap the values without the need of an additional variable:

#define SWAP(a, b) \
    { \
        (a) ^= (b); \
        (b) ^= (a); \
        (a) ^= (b); \
    }

如果要交换复杂类型(浮点数,结构等),则需要一个辅助变量:

If you're swapping complex types (float, structs, ...) you need a helper variable:

#define SWAP_TYPE(type, a, b) \
    { \
        type __swap_temp; \
        __swap_temp = (b); \
        (b) = (a); \
        (a) = __swap_temp; \
    }

这两个宏的用法如下:

int a = 6;
int b = 123;
float fa = 3.1415;
float fb = 2.7182;

SWAP(a, b);
SWAP_TYPE(float, fa, fb);

这篇关于定义一个预处理宏交换(T,X,Y)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆