简体   繁体   English

什么是使用条件运算符的其他什么都不做?

[英]What is the equivalent of else do nothing using the conditional operator?

I want to know what is the equivalent of this if statement: 我想知道if语句的等价物:

if (condition) {
        // do something
    }else{
        // do nothing

    }

Using the conditional operator: 使用条件运算符:

(condition) ? // [do nothing] : {do nothing} "

It's not possible to "do nothing" using the conditional operator. 使用条件运算符不可能“无所事事”。 You always have to have valid expressions on both sides, although both expressions can be casted to void . 你总是必须在两边都有有效的表达式,尽管这两个表达式都可以被转换为void

This is one of the dis-advantage of ternary operator ( ?: ). 这是三元运算符(?:)的不利之处。

It needs expressions in all the three places. 它需要三个地方的表达。 You cant skip any of them. 你不能跳过他们中的任何一个。

You can do some tweak on it, however its True-part and / or False-part can be assigned to the same as : 您可以对其进行一些调整,但其True-part和/或False-part可以分配给:

int big=100;
big= (10 > 100) ? 0 : big;
if (!condition) {
        // do something
    }else{
        // do nothing

    }

Take a look at the !before contition now :-) 现在看一下!之前的汇款:-)

The ! 的! before the condition just switches the "if", to "if not"... 条件之前只需将“if”切换为“if not”......

Is that what you have been searching for? 那是你一直在寻找的吗?

originalValue = (condition) ? newValue : originalValue

The compiler should then remove the unnecessary assign of originalValue to itself. 然后编译器应该删除对原来不必要的originalValue赋值。

GCC had an extension to do give you something more to what you where looking for, something like 海湾合作委员会有一个扩展,可以给你更多的东西给你所寻找的东西,比如

originalValue = condition ?: newValue;

So it may be available in clang also. 因此它也可以在clang中使用。 You would have to ! 你必须! the condition though. 虽然条件。

In normal code the answer is there is no equivalent - all sub expressions of an expression must have a value, but... 在普通代码中,答案是没有等价的 - 表达式的所有子表达式都必须有一个值,但......

the following is not a recommendation 以下不是推荐

Something along the lines of the following should work in the general case: 以下内容应该适用于一般情况:

condition ? ( (^{ do something })(), 0 ) : 0;

That is for the general case. 这是一般情况。 If do something is a single, non-compound, statement; 如果做某事是单一的,非复合的,陈述; such as a method call; 如方法调用; then the block can be dropped to give: 然后可以删除该块以给出:

condition ? (do something, 0) : 0;

Again this is NOT recommended in real code! 在实际代码中不建议这样做!

你可以做这样的事情

someBool ? [self someFunction] : (^{})(); //empty block

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM