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

2020-04-18 08:28发布

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 !

6条回答
男人必须洒脱
2楼-- · 2020-04-18 08:50
condition ? first statement : second statement

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

查看更多
神经病院院长
3楼-- · 2020-04-18 09:02

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!

查看更多
【Aperson】
4楼-- · 2020-04-18 09:08

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);
}
查看更多
Juvenile、少年°
5楼-- · 2020-04-18 09:13

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楼-- · 2020-04-18 09:14

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.

查看更多
做个烂人
7楼-- · 2020-04-18 09:14

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

查看更多
登录 后发表回答