Uses the assignment operator in an argument to an undefined function?

I found code like this in an example that my university professor wrote.

int main(){
    int a=3;
    int b=5;
    std::vector<int>arr;
    arr.push_back(a*=b);
    std::cout<<arr[0]<<std::endl;
}

Is there any clear behavior for this? Will there arr[0]be 3 or 15 (or something else completely)? Visual Studio prints 15, but I have no idea how other compilers react.

+4
source share
3 answers

Before push_back is executed, the expression passed as an argument must be evaluated. So what is the meaning a *= b. Well, it will always be a * b, and a new value awill be set to that.

+4
source

, .

, "".

auto& temp = (a*=b);
arr.push_back(temp);
+3

The value of an expression with a compound assignment operator is the value of the left operand after assignment. So the code you showed is valid. Moreover, in C ++ (opposite to C), the result is lvalue. So you can even write :)

arr.push_back( ++( a *= b ) );

In this case, the following statement outputs 16. :)

+1
source

Source: https://habr.com/ru/post/1627015/


All Articles