问题
this code doesn't work
int main(){
cout << 5 ? (5 ? 0 : 2) : 5;
system("pause");
return 0;
}
this code works
int main(){
cout << (5 ? (5 ? 0 : 2) : 5);
system("pause");
return 0;
}
can't understand why?
回答1:
cout << 5 ? (5 ? 0 : 2) : 5;
is parsed as
(cout << 5) ? (5 ? 0 : 2) : 5;
回答2:
This is due to operator precedence rules.
<<
has higher precedence than ?
, so your first expression is parsed as:
(cout << 5) ? (5 ? 0 : 2) : 5;
Brackets are necessary in this case to get the parse you want.
来源:https://stackoverflow.com/questions/31183993/c-ternary-operator-and-cout