0

Consider the following (a bit tricky) loop in C++:

using namespace std;

list<string> lst;
// Fill the list with some strings or keep it empty depending on something...

auto i = lst.begin(), e = lst.end();
string csv;
if(lst.size())
  do
    csv += *i;
  while(++i != e && (csv += ", ", true));

The aim of it is to form the coma-separated string consisting of the initial list members. And it handle right the case of empty list. But I'm in doubt, if the second part of the while condition may be optimised out by some (too) smart compiler. Is there any explanations in the standard on the cases like this one?

I understand that this "task" can be fulfilled via different ways, but I'm querying not about the CSV-string forming algorithm here.

Thank you.

Serge Roussak
  • 1,731
  • 1
  • 14
  • 28

2 Answers2

2

The C++ standard permits optimizations only if they have no observable effects.

In this case the 2nd half of the while condition cannot be completely eliminated, because this will have an observable effect. C++ compilers will not remove it.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
  • To be pedantic, there are rare cases where optimisation is allowed with observable behaviors (NRVO, new expression, floating-point exceptions) see [as-if rule](https://en.cppreference.com/w/cpp/language/as_if#Notes) for details. – Jarod42 Feb 09 '23 at 15:47
1

Optimizations are not allowed to change the behavior of your code. So independent of optimizations, your code will always do what you wrote down. That is assuming your code is valid C++ and has no undefined behavior.

Regarding your actual code, I would generally recommend being less clever in order to get easier to understand and maintain code:

std::string csv;
bool first = true;
for (std::string entry : lst) {
  if (!first) {
    csv += ", ";
  }
  first = false;
  csv += entry;
}

Unlike your code this will also work correctly for empty lists.

Chronial
  • 66,706
  • 14
  • 93
  • 99
  • Alternative ways of [idiom-for-iterating-between-each-consecutive-pair-of-elements](https://stackoverflow.com/questions/35372784/idiom-for-iterating-between-each-consecutive-pair-of-elements/35373017#35373017). – Jarod42 Feb 09 '23 at 15:50