里用C实现通用互换宏 [英] Implement generic swap macro in C
问题描述
可能重复:结果
有c)中一个std的等价交换::( >
乡亲
我试图一个问题写在C和我的宏如下的通用互换宏是这样的:
I was attempting a problem to write a generic swap macro in C and my macro looks like this:
#define swap(x,y) { x = x + y; y = x - y; x = x - y; }
它工作正常的整数和浮点数,但我不确定是否有在任何捕捞。如果用一般的宏观他们的意思是交换指针,人物等?谁能帮我写一个通用的宏交换每个输入?
It works fine for integers and floats but I am unsure if there is any catch in it. What if by generic macro they mean swapping pointers, characters etc ? Can anyone help me with writing a generic macro for swapping every input ?
感谢
推荐答案
这仅整数效果很好。
有关花车它会失败(例如试图用一个非常大的浮动和一个非常小的运行它)。
For floats it will fail (e.g. try running it with a very large float and a very small one).
如下我建议的内容:
#define swap(x,y) do \
{ unsigned char swap_temp[sizeof(x) == sizeof(y) ? (signed)sizeof(x) : -1]; \
memcpy(swap_temp,&y,sizeof(x)); \
memcpy(&y,&x, sizeof(x)); \
memcpy(&x,swap_temp,sizeof(x)); \
} while(0)
memcpy的是,当拷贝量在编译的时候被称为优化pretty。
此外,还有无需手动传递一个类型名称或使用编译器的扩展。
memcpy is pretty optimized when the amount to copy is known at compilation time. Also, there's no need to manually pass a type name or use compiler specific extensions.
这篇关于里用C实现通用互换宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!