Different behaviour of comma operator in C++ with return?

后端 未结 4 622
清歌不尽
清歌不尽 2021-02-01 11:40

This (note the comma operator):

#include 
int main() {
    int x;
    x = 2, 3;
    std::cout << x << \"\\n\";
    r         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 12:28

    The comma (also known as the expression separation) operator is evaluated from left to right. So return 2,3; is equivalent to return 3;.

    The evaluation of x = 2,3; is (x = 2), 3; due to operator precedence. Evaluation is still from left to right, and the entire expression has the value 3 with the side-effect of x assuming the value of 2.

提交回复
热议问题