简写 C++ if else 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24793916/
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
shorthand c++ if else statement
提问by kevorski
So I'm just curious if there is a short hand statement to this:
所以我很好奇是否有一个简短的声明:
if(number < 0 )
bigInt.sign = 0;
else
bigInt.sign = 1;
I see all these short hand statements for if a < b and such.
我看到所有这些关于 if a < b 等的简短陈述。
I'm not sure on how to do it properly and would like some input on this.
我不确定如何正确地做到这一点,并希望对此提供一些意见。
Thanks!
谢谢!
I actually just figured it out right before you guys had answered.
我实际上只是在你们回答之前就想通了。
I'm using bigInt.sign = (number < 0) ? 1 : 0
我正在使用 bigInt.sign = (number < 0) ? 1 : 0
回答by Bla...
The basic syntax for using ternary operator is like this:
使用三元运算符的基本语法是这样的:
(condition) ? (if_true) : (if_false)
For you case it is like this:
对于你的情况,它是这样的:
number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;
回答by Bla...
try this:
尝试这个:
bigInt.sign = number < 0 ? 0 : 1
回答by M.M
Yes:
是的:
bigInt.sign = !(number < 0);
The !
operator always evaluates to true
or false
. When converted to int
, these become 1
and 0
respectively.
该!
运营商始终计算为true
或false
。当转换为 时int
,它们分别变为1
和0
。
Of course this is equivalent to:
当然,这相当于:
bigInt.sign = (number >= 0);
Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true
or false
.
这里的括号是多余的,但为了清楚起见,我添加了它们。所有比较和关系运算符的计算结果都为true
或false
。
回答by Fantastic Mr Fox
Depending on how often you use this in your code you could consider the following:
根据您在代码中使用它的频率,您可以考虑以下几点:
macro
宏
#define SIGN(x) ( (x) >= 0 )
Inline function
内联函数
inline int sign(int x)
{
return x >= 0;
}
Then you would just go:
然后你就去:
bigInt.sign = sign(number);