问题
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?
Example:
int a = 0;
a > 10 ? a = 5 : /*do nothing*/;
Using a
seems to do the trick, but I am wondering if there is a more generally accepted way.
回答1:
That will do it:
a = a > 10 ? 5 : a;
or simply:
if (a > 10) a = 5;
回答2:
Another option:
a ? void(a = 0) : void();
What's good about this one is that it works even if you can't construct an instance of decltype(a = 0)
to put into the 'do nothing' expression. (Which doesn't matter for primitive types anyway.)
回答3:
You can also use a logical expression (though maybe confusing) in case you don't want to use an if statement.
a > 10 && a = 5
回答4:
You can do:
a > 10 ? a=5 : 0;
But, I would prefer:
if (a > 10)
a = 5;
来源:https://stackoverflow.com/questions/44988201/do-nothing-in-the-else-part-of-the-ternary-operator