简体   繁体   中英

C++ Conditional Operator

I once seen a -wired- operator in C++ which assigns value if greater than..
it was a combination of ? , < and =

eg let x = value if value is greater than x

I x=(x<value)x:value x=(x<value)x:value

It was some sort of x<?=value

But I can not remember it exactly, and can not find it online... Can some one remind me of it?

Thanks,

There is no operator that assigns variables based on their relative values.

However, there is the ?: operator:

x = value > x ? value : x;

If you read it out loud from left to right, it makes sense.

gcc has -- in version 3.3.6 at least! -- a gcc-specific language extension providing specialized operators for implementing min and max. Perhaps this is what you are thinking of?

Minimum and Maximum Operators in C++

I don't have gcc handy to test it with, but it might have an updating form, too.

怎么样:

(x<value) || (x=value)

你在想三元运算符吗?

result = a > b ? x : y;
x = x < value ? 0 : 1;

此函数将x设置为0是x <值,否则为1。

it's a more convenient version of an if statement that is used for assignment

int x = (some bool) ? trueval : falseval;

this is roughly what it means, when the bool is evaluated it either gets the trueval or falseval depending on the outcome, it's easier than saying

int x;
if (someval)
    x = trueval;
else
    x = falseval;

I suspect what you're thinking of is a gcc extension 1 that lets you leave out the middle operand to the conditional operator, so (for example):

a = b ? b : c;

can be written as:

a = b ?: c;

1 Despite the '2.95.3' in the URL, I'm not aware of a newer version of the linked page. If somebody is, please feel free to point it out (or edit it in).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM