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

后端 未结 4 615
清歌不尽
清歌不尽 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:19

    This statement:

      x = 2,3;
    

    is composed by two expressions:

    > x = 2
    > 3
    

    Since operator precedence, = has more precedence than comma ,, so x = 2 is evaluated and after 3. Then x will be equal to 2.


    In the return instead:

    int f(){ return 2,3; }
    

    The language syntax is :

    return 
    

    Note return is not part of expression.

    So in that case the two expression will be evaluated will be:

    > 2
    > 3
    

    But only the second (3) will be returned.

提交回复
热议问题