Is "} while (0);" always equal to "break;}, and (1);"?

I compared gcc assembler output

do{ //some code }while(0); 

from

 do{ //some code break; }while(1); 

The output is equal, with or without optimization, but ..

It's always like this?

No experiment can prove a theory, they can only show that they are wrong

+4
source share
6 answers

There is a slight difference:

 do { // code if ( condition ) continue; // code break; } while(1); 

The loop will restart when the condition is true, whereas in the version } while(0); a continue value will be equivalent to break .

If there is no continue , then they should return the exact same code.

+18
source

Forms are not equivalent. This is an infinite loop:

 do { continue; break; } while (1); 

Is not:

 do { continue; } while (0); 
+5
source

Edit: After reading various comments on this, I will acknowledge that this answer is incorrect. Unfortunately.

Instead:

 do{ //some code }while(0); 

or

 do{ //some code break; }while(1); 

I would just use:

 //some code 

I'm not 100% sure if you can do this in C ++, but if you want to limit the scope of variables, and that is why you do it, just use curly braces yourself:

 { // Some Code } 
+4
source

Markus comment pointed me to this answer: the difference is in using the continue keyword.

In this case:

 int _tmain(int argc, _TCHAR* argv[]) { int i = 0; do { ++i; _tprintf(_T("Iteration %d\n"), i); if (i < 30) continue; } while(0); return 0; } 

you only get one iteration, while in this case:

 int _tmain(int argc, _TCHAR* argv[]) { int i = 0; do { ++i; _tprintf(_T("Iteration %d\n"), i); if (i < 30) continue; break; } while(1); return 0; } 

you get iteration 30 . Tested under VS2008.

+4
source

The do while statements are logically equivalent. If they are translated into the same byte code, it depends on the compiler. I think that most modern compilers will treat them the same way.

+3
source

EDIT based on your comment that you use time with break to be able to break out of the loop when certain conditions are met.

If this is what you are trying to accomplish:

 do { // processing step 1 if( some_condition ) break; // processing step 2 if( some_condition ) break; // etcetera.. } while(0) 

... then just fold the code that you have in your while loop into a standalone function with several return values:

 void processing() { // processing step 1 if( some_condition ) return; // processing step 2 if( some_condition ) return; // etcetera.. } int main() { // ... processing(); return 0; } 
0
source

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


All Articles