Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

c++ - Right Associativity of Ternary Operator

std::cout << (true ? "high pass" : false ? "fail" : "pass")

is the same as

std::cout << (true ? "high pass" : (false ? "fail" : "pass"))

Since the ternary operator is right associative, why don't we perform the right-hand operation first? Shouldn't pass be printed instead of high pass?

question from:https://stackoverflow.com/questions/65641518/operator-associativity-and-the-conditional-operator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You misunderstood operator associativity. It's simply the way to group operators with the same precedence and doesn't affect order of evaluation in any way. So cond1 ? 1 : cond2 ? 2 : cond3 ? 3 : 4 will be parsed as

cond1 ? 1 : (cond2 ? 2 : (cond3 ? 3 : 4))

from the right and not as

((cond1 ? 1 : cond2) ? 2 : cond3) ? 3 : 4

which groups operands from the left. Once parentheses are added then the expression will be evaluated in its normal order

In fact PHP made the ternary operator left-associative which is one of its biggest mistake and it's unfixable by now


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...