Multiple statements if condition is true in shorthand if

陌路散爱 提交于 2019-12-11 03:58:41

问题


I recently discovered the shorthand if statement and after searching online I couldn't find a definite answer.

Is it possible to execute 2 statements if the condition is true/false?

int x = (expression) ? 1 : 2;

for example

int x = (expression) ? 1 AND 2 : 3;

Seeing as i haven't comne across a example where they used it I guess it's not possible but I wouldn't want to miss out.


回答1:


You're talking about conditional assignment. You should look at what is defined by what you've written:

int x = (expression) ? 1 AND 2 : 3;

That is evaluating 'expression' and if true executing '1 AND 2' then assigning the value to x. If 'expression' evaluated to false, '3' is evaluated and assigned to x. Hence you could definitely do something like this:

int x = (expression) ? GetInt1() + GetInt2() : 345;

What is important is that what you have found is not just a shorthand if. It is conditional assignment.




回答2:


You can't have a statement return two values and that's all that ternary does. It is not a shorthanded if it is a method persay that returns values



来源:https://stackoverflow.com/questions/6299632/multiple-statements-if-condition-is-true-in-shorthand-if

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