C++, ternary operator and cout

后端 未结 2 1171
情话喂你
情话喂你 2021-01-28 05:01

this code doesn\'t work

int main(){
cout << 5 ? (5 ? 0 : 2) : 5;
system(\"pause\");
return 0;
}

this code works

int main(         


        
相关标签:
2条回答
  • 2021-01-28 05:31

    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.

    0 讨论(0)
  • 2021-01-28 05:40
    cout << 5 ? (5 ? 0 : 2) : 5;
    

    is parsed as

    (cout << 5) ? (5 ? 0 : 2) : 5;
    
    0 讨论(0)
提交回复
热议问题