Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 557
tomatopipps Avatar asked Feb 07 '23 20:02

tomatopipps


1 Answers

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.

like image 142
Ivaylo Strandjev Avatar answered Feb 16 '23 02:02

Ivaylo Strandjev