-1

First, Let me define how I understand operator associativity: Associativity dictates what operation goes first when two operands have the same precedence. If my understanding of associativity is correct, then can someone explain the following: 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?

JayYay
  • 27
  • 3
  • So, particularly [this answer](https://stackoverflow.com/a/7407388/2757035) from the dupe. – underscore_d Jan 08 '21 at 16:53
  • 1
    Assuming that `false ? "fail" : "pass"` *were* evaluated first, how could the value of the entire expression be `"pass"`? Are you assuming that determining the value of the inner expression somehow bypasses the outer condition? – molbdnilo Jan 08 '21 at 17:01
  • The equivalent using `if` and `else` is `if (true) std::cout << "high pass"; else if (false) std::cout << "fail;" else std::cout << "pass"; `. – molbdnilo Jan 08 '21 at 17:11

1 Answers1

0

Your example is essentially:

(true ? "high pass" : (false ? "fail" : "pass"))

Or more simply, evaluating the conditional:

(true ? "high pass" : "pass")

So of course it evaluates to high pass.

Tumbleweed53
  • 1,491
  • 7
  • 13