C 中的 MAX 和 MIN 是什么?#定义函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15062967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:58:28  来源:igfitidea点击:

What are the MAX and MIN in C? #define function

c++cmaxc-preprocessormin

提问by José Algarra

I am a student and my teacher gave me and exercise already solved for studying, in his exercise I see this line:

我是一名学生,我的老师给了我并且已经解决了学习的练习,在他的练习中我看到了这一行:

 #define MIN(a,b) ((a) < (b) ? (a) : (b))

I never used the #define before.

我以前从未使用过#define。

I do not understand what:

我不明白什么:

((a) < (b) ? (a) : (b))

stands for.

代表。

Looks like if '?' was a comparer not sure. Anybody can help me?

看起来像如果 '?' 是一个比较者不确定。任何人都可以帮助我吗?

回答by RvdK

It's called the conditional operator (or ternary operator)

它被称为条件运算符(或三元运算符)

#define MIN(a,b) ((a) < (b) ? (a) : (b))

Means:

方法:

if ((a) < (b)){   
  return a;  
} else {   
  return b; 
}

So if you would do:

所以如果你会这样做:

int test = MIN(5,10);

test would be 5

测试将是 5

Troubles linking to the wiki page: http://goo.gl/bw2sL

无法链接到 wiki 页面:http: //goo.gl/bw2sL

回答by 111111

#definedefines a new preprocessor macro, which in this case place's the MIN code at the point where you place it; with the aand b"variables" being replaced with whatever you gave to the macro as inputs.

#define定义了一个新的预处理器宏,在这种情况下,它将 MIN 代码放置在您放置它的位置;随着ab“变量”正在与任何替换你给宏作为输入。

 #define MIN(a,b) ((a) < (b) ? (a) : (b))

 MIN(5,6);
 //gets expanded to
 ((5) < (6) ? (5) : (6))

The actual expression is using the ternary operator to, do return either A or B depending on the evaluation of the expression, you can read more about it here:

实际表达式使用三元运算符,根据表达式的计算返回 A 或 B,您可以在此处阅读有关它的更多信息:

http://en.cppreference.com/w/cpp/language/operator_other

http://en.cppreference.com/w/cpp/language/operator_other

Finally, as you marked your question with c++, please consider the non macro max and min functions.

最后,当您用 C++ 标记您的问题时,请考虑非宏 max 和 min 函数。

#include <algorithm>
...
int i=std::min(5,6);