MIN宏如何工作? [英] How does this MIN macro work?
问题描述
如果这是一个愚蠢的问题,请原谅我.我似乎无法弄清楚以下MIN宏的工作原理:
Pardon me if this is a dumb question. I can't seem to figure out how the following MIN macro works:
#define MIN(x, y) (y) ^ ((x ^ y) & -(x < y))
推荐答案
宏是预处理器指令,这意味着无论在何处使用宏,都将被相关的代码段取代.
A macro is a pre-processor directive, meaning that wherever it's used, it will be replaced by the relevant piece of code.
如果您在自己的MIN
宏中进行编辑,那么我或此处的其他人应该可以帮助您进行解释.
If you edit in your MIN
macro, me or someone else here should be able to help explain it.
示例:
#include<stdio.h>
#define PLUS +
int main() {
printf("%d", (1 PLUS 3));
}
这应该只输出4
.
让我们分解一下宏.
我们有
(y) ^ ((x ^ y) & -(x < y))
-
让我们来看最后一部分,
(x < y)
.如果x
小于y
,并且小于1
,则为1
.因此,如果x
较小,则-(x < y)
将为0xffffffff
,否则为0
.Let's take the last part,
(x < y)
. This is1
ifx
is smaller thany
and1
else. Therefore,-(x < y)
would be the0xffffffff
ifx
is smaller and0
else.所以现在,如果x小于y,则
((x ^ y) & -(x < y))
变为((x ^ y) & 0xffffffff)
,即(x ^ y)
,否则变为((x ^ y) & 0)
,即0
.So now,
((x ^ y) & -(x < y))
becomes((x ^ y) & 0xffffffff)
, i.e.,(x ^ y)
, if x is smaller than y, and((x ^ y) & 0)
, i.e.,0
else.因此,如果x较小,则整个宏将变为
(y) ^ (x ^ y)
,即x
,否则将变为(y) ^ 0
,即y
.这确实是必需的MIN
功能.Therefore, the entire macro becomes
(y) ^ (x ^ y)
, i.e.,x
, if x is smaller and(y) ^ 0
, i.e.,y
else. This is indeed theMIN
functionality required.这篇关于MIN宏如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!