0
  1. 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.

  1. 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;
  1. Generally, is it a bad practice to use increments/decrements in expressions?
mentalmushroom
  • 2,261
  • 1
  • 26
  • 34
  • 3
    3. if you write the code you presented as alternative equivalents then there would be no doubt how it is evaluated. Knowing details about sequence points is good, but writing code that doesnt require you to know that details is better imho ;) – 463035818_is_not_an_ai Jun 30 '22 at 14:03
  • _Generally, is it a bad practice to use increments/decrements in expressions?_ No. _Is it a bad idea to use more than one for the same variable?_ Definitely. – Paul Sanders Jun 30 '22 at 14:15

0 Answers0