C++_comma operator

The comma in C++ can be used as an operator, its function is to connect the left and right expressions,
such as: 3+5, 6+8;
it will first execute the expression on the left of the comma and then execute the expression on the right of the comma, two expressions After the formulas are calculated, the expression on the right is used as the result of the final expression.
E.g:

#include <iostream>

int main()
{
    
    
    int a;
    //这里加括号是因为赋值运算等级要高于逗号运算
    a = (3 + 5, 8 + 8);
    std::cout << "a="<<a<<std::endl;
}

The result is a=16;
another example:

#include <iostream>

int main()
{
    
    
    int a,b;
    b=(a = 3 * 5, a * 4);

    std::cout << "a="<<a<<std::endl;
    std::cout << "b=" << b << std::endl;
}

The result is a=15, b=60.
This is because in the comma expression (a = 3 * 5, a * 4), the priority of the assignment operator is higher than that of the comma operator, so first solve a=3× 5. At this time, after calculation and assignment, the value of a is 15;
after solving a×4, the value of the entire expression (a = 3 * 5, a * 4) is 60, and then assigned to b, so b = 60. At this time, since it is not an assignment operation, the value of a is still 15.

Guess you like

Origin blog.csdn.net/qq_43530773/article/details/112688246