“Do nothing” in the else-part of the ternary operator?

不想你离开。 提交于 2021-02-05 08:42:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!