- Consider an example of finding a median of a vector containing even number of elements:
std::vector<double> v{ 3,5,2,8,1,2 };
auto itMid = v.begin() + v.size() / 2;
std::partial_sort(v.begin(), itMid+1, v.end());
auto med = (*itMid + *--itMid)/2.0;
I am wondering whether the last line will always be evaluated as
auto tmp1 = *itMid;
--itMid;
auto tmp2 = *itMid;
auto med = (tmp1 + tmp2) / 2.0;
rather than
--itMid;
auto tmp1 = *itMid;
auto tmp2 = *itMid;
auto med = (tmp1 + tmp2) / 2.0;
I read that the evaluation order of operator operands and subexpressions, also the order in which side effects take place, is unsequenced. That is, we can expect both scenarios, right? Having said that, MSVC and GCC seem to behave the same way and follow the first option.
- Let's alter the code:
std::vector<double> v{ 3,5,2,8,1,2 };
auto itMid = v.begin() + v.size() / 2;
std::partial_sort(v.begin(), ++itMid, v.end());
auto med = (*--itMid + *--itMid)/2.0;
In this case it does not seem to matter which decrement is evaluated first. But is it still possible that the code would be evaluated as
--itMid;
--itMid;
auto tmp1 = *itMid;
auto tmp2 = *itMid;
auto med = (tmp1 + tmp2) / 2.0;
- Generally, is it a bad practice to use increments/decrements in expressions?