Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why operator `?:` does not have priority?

Tags:

c++

After debugging I found that ternary operator ?: does not have priority. My question is why?
I have the following code:

bool T = true;
cout << ((T == true) ? "true" : "false") << endl;
cout << (T == true) ? "true" : "false";

Output:

true
1

live demo: http://ideone.com/Tkvt9q

like image 416
Quest Avatar asked Sep 10 '25 03:09

Quest


1 Answers

The conditional operator does have a precedence (albeit slightly complicated by its ternary nature); but that precedence is very low. Since it's lower than <<, the second is parsed as

(cout << (T == true)) ? "true" : "false";

streaming the boolean value of T == true, then evaluating (but ignoring) the expression "true". Most compilers will give a warning, if you enable a sensible set of warnings.

Here is a reference to the operator precedences, showing << with a higher precedence (7) than ?: (15): http://en.cppreference.com/w/cpp/language/operator_precedence

like image 185
Mike Seymour Avatar answered Sep 12 '25 16:09

Mike Seymour