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
  • 375
  • 1
  • 8
  • 20

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,099
  • 5
  • 36
  • 42
1
if (cond)
   do_something(exp);
else 
   do_something_else(exp);

would not be valid C.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
1

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

Hogan
  • 69,564
  • 10
  • 76
  • 117