2

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

Hello, in many C macros programmers use special one-loop, for example:

#define do_something(a) do { execute(a); count(a); } while(0)

because of when you want to do this macro in loop and you don't use "{}". Why they aren't using simple block instead? I mean, doesn't

#define do_something(a) { execute(a); count(a); }

have the very same effect?

Community
  • 1
  • 1
Garret Raziel
  • 355
  • 7
  • 19

3 Answers3

5

Because

if( something ) do_something(a);
else something_else();

expands to:

if( something ) do { execute(a); count(a); } while(0);
else something_else();

which is correct, but:

if( something ) { execute(a); cout(a); };
else something_else();

would not be correct (the superfluous ";").

Frunsi
  • 7,019
  • 5
  • 34
  • 42
1
if (cond)
   do_something(exp);
else 
   do_something_else(exp);

would not be valid C.

AProgrammer
  • 49,582
  • 8
  • 87
  • 140
1

Another reason for this: You can use break to get out of the while loop.

Hogan
  • 65,989
  • 10
  • 76
  • 113