Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

May the part of conditional expression be optimised out?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading