Does the construct contain .. while (false) contributes to a better control flow?

I recently met this code:

do { if ( ! checkSomething() ) break; // some code if ( ! checkSomeOtherThing() ) break; // some other code } while(false); // some final code 

The programmer who wrote it wrote a comment on the lines "cleaner control flow" .

In my opinion, the source code may look better if you reorganize it into something else. But is this statement true? Is this design good?

+3
source share
4 answers

If you don't mind loops containing multiple break statements, then the only problem here is that C (for obvious reasons) doesn't allow you to break out of the bare block, hence the β€œnon-loop”, which is some kind of unsuspecting future the maintainer could be wrong for the real cycle.

Considerations, I think, are as follows:

  • if there are only two break points, what's bad about the two if ?
  • if there are more than two breakpoints, then indentation with if can become unpleasant, and this saves it, but again, does the function do too much? And even if this is not the case, would it be better to just use goto and avoid the weirdness of a loop that doesn't loop?

Since you put this agnostic language, I used the mock assembler language with block ... endblock from which you could break out. This leads to reasonably good code for checking the necessary conditions, for example:

 block breakif str1 == null breakif str2 == null get some combined property of str1 and str2 breakif some other condition that stops us getting on with it get on with it endblock 

Actually it was not breakif str1 == null , it was breakifeq.p str1, null , or something like that, but I forgot exactly what.

+2
source

It is much easier for me to read, and it gives an identical result:

 if ( checkSomething() ) { // some code if ( checkSomeOtherThing() ) { // some other code } } // some final code 

I think that do ... while usually difficult to follow, but using it for something other than a loop is misleading at best.

+6
source

This is equivalent to a goto .

In such situations, it's better to use goto than to use an ugly hack.

Changing it to use goto makes it more readable:

 if (!checkSomething()) goto Done; // some code if (!checkSomeOtherThing()) goto Done; // some other code Done: //some final code 
+3
source

I saw that the do-while form is accepted as the standard to which encoders conform. The advantage is that it transfers and implements that the loop will always be executed at least once. This helps isolate, with consistency, situations when something else happens, that is, where the code in the loop is not executed.

This standard was adopted because the Warnier-Orr technique was used.

0
source

Source: https://habr.com/ru/post/1332095/


All Articles