What does “?” and “:” do in boolean statements? [duplicate]

♀尐吖头ヾ 提交于 2019-12-04 05:19:48

问题


I think this question is a general programming question, but let's assume I'm asking this for Java.

what does the following statement do ?

return a ? (b || c) : (b && c);

I have seen the syntax with ?'s and :'s in many topics at SO, this particular one I found in Check if at least two out of three booleans are true

But I don't know what they mean, so how to use them, and I believe it's something very useful for me.

Thanks !


回答1:


That's the conditional operator. It means something like:

condition ? value-if-true : value-if-false;

So in your case, it returns b || c if a is true, and b && c if a is false.




回答2:


This is known as a ternary statement; it's shorthand for an if-else block - you can google that for more info.

Your example is equivalent to

if (a) {
   return (b || c);
} else {
   return (b && c);
}



回答3:


condition ? first statement : second statement

if condition is true then first statement is executed otherwise the second statement




回答4:


It's the ternary operator, the whole statement expands to something more like this:

if a == true then
  if b == true or c == true then
    return true
else 
  if b == true and c == true then
    return true

As your link says a much more elegant way to check if at least 2 out of three booleans are true when applied in this way!




回答5:


its an conditional operator... jst like if and else....

e.g----

a<b ? 4 :5      where a= 2 and b=5

as a is less then b.... then this operator will return 4... else it return 5....

in short... if your condition i.e statement before ? is correct then it returns 1st value.. i.e statement before colon.... else it returns 2nd value......




回答6:


According to your code, return a ? (b || c) : (b && c);

Result will be like this :

if a == true , then result = b || c otherwise result = b && c

its a ternary operator & used in most of the languages C,C++, java, Javascript



来源:https://stackoverflow.com/questions/16910359/what-does-and-do-in-boolean-statements

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