Three-mesh operator "?:" Omit middle operand

Source: Internet
Author: User

turn from: http://blog.csdn.net/road_dongliang/article/details/48134993

When using the three-mesh operator, what we often see is:

X? X:y

is the shorthand for if else

If x is true, it returns x, and if x is false, it returns Y. This is the simplest and most basic usage.

But sometimes you see this usage.

X?: Y

。 And: There is no operand between, what is the use of this?

After experimenting with several examples, guess. With: omitted the x between

Which means X? : Y is x? X:y

It's going to make sense.


So the shape of a > B?: b What is omitted in the middle, is a?

After verification, it's not a.

Actually omitted a > b

Which means a > b?: B is equivalent to a > b? A > B:b

Then it can be concluded that: ". : "The middle of the omitted Dongdong is with". "The previous number or expression is exactly the same.


It's worth noting that, in some cases, there will be discrepancies.

such as Y = ++x? ++x:3 and y = ++x?: 3

The output of the Y results are not the same, and this is why.

When the initial value of x is 0 o'clock, the result of the output y of the first one is 2, and the output Y of the second type is 1.

The first one is the result of performing two + + operations, while the second method performs only one + + operation

So when there is + + or--operation, to judge according to need not to omit, can not be hastily omitted, resulting in unnecessary errors


In fact, this kind of ellipsis is very good, especially when the length of the code is relatively long, you can meet the requirements of the premise of simplifying the code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.