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

2020-04-18 08:45发布

问题:

This question already has answers here:
Closed 6 years ago.

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