C++, ternary operator and cout

倾然丶 夕夏残阳落幕 提交于 2021-02-05 09:32:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!