Search code examples
c++undefined-behavioroperator-precedence

Is using an assignment operator in a function argument undefined behaviour?


I found some code similar to this in an example my university tutor 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 a well-defined behaviour for this? Would arr[0] be 3 or 15 (or something else entirely)? Visual Studio outputs 15, but I have no idea if that's how other compilers would respond to it.


Solution

  • Before push_back is executed, the expression passed as argument will need to be computed. So what is the value of a *= b. Well it will always be a * b and also the new value of a will be set to that one.