Do {} while (0) vs. if (1) {} in macros

Possible duplicate:
Why are sometimes meaningless do / while and if / else statements in C / C ++ macros?

When you need to execute several statements in a preprocessor macro processor, it is usually written as

#define X(a) do { f1(a); f2(a); } while(0) 

therefore, when this macro is used inside expressions like:

 if (...) X(a); 

he will not be spoiled.

Question: wherever I saw such an expression, it always do { ... } while(0); . Is there any reason to prefer such a concept (in my opinion, clearer) if (1) { ... } ? Or am I mistaken in my observations, and they are equally popular?

+4
source share
5 answers

No, you are not mistaken.

Actually a good reason:

 #define my_code if (1) { ... } if (1) my_code; 

Problem with ; ! It should not be ... and it will look strange, and not in the spirit of language. You can either choose a code that extends to two ; in line, or code that looks non-c-ish :)

The do-while construct, on the other hand, does not have this problem.


In addition, as mentioned above, there is an else problem:

 if (1) my_code; else { ... } 

Ignoring ; issuse, the else block now belongs incorrectly if.

+7
source

if can be as safe as do/while only if there is an else branch. For instance:.

 #define X(a) if(1) { f1(a); f2(a); } else{} 

Safe as:

 #define X(a) do { f1(a); f2(a); } while(0) 

So the user cannot do this:

 X(...) else ...; 

One difference is that when using do/while at the end is required ; whereas if/else does not work.

+7
source

Consider this:

 if(foo) X(a); else whatever(); 

This will expand to:

 if(foo) if(1) { ... } else whatever(); 

This is bad because now else belongs to the wrong one if.

+4
source

Using do... while , you can break exit if necessary.

+2
source

When you use the form #define X(a) do { ... } while(0) , it forces you to put ; at the end of instruction X(1) .

+2
source

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


All Articles