简写 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

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

shorthand c++ if else statement

c++if-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 trueor false. When converted to int, these become 1and 0respectively.

!运营商始终计算为truefalse。当转换为 时int,它们分别变为10

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 trueor false.

这里的括号是多余的,但为了清楚起见,我添加了它们。所有比较和关系运算符的计算结果都为truefalse

回答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);