Feb
26

What’s the need of using encapsulation { do..while(0) block } in define a macro in C programming?

While reading many codes in c programming based open source project i came to know one interesting things. Let me explain you by some sample code.

#define Assert(v)   if(!(v)) printf("Error occurred at: %s, in %s at %i",  #v, __FILE__, __LINE__);

At most of the experienced people used to write such macro in following style

 #define Assert(v)   do { if(!(v)) printf("Error occurred at: %s, in %s at %i",  #v, __FILE__, __LINE__); } while(0)

This method is called as making encapsulating our macro.

Now let me explain you whats the need of this….

see if you havent  encapsulated your macro then

case 1: if you will call that macro with ; 

int main()
{
Assert(0);
return 0;
}

here it will expand as

int main()
{
if(!(v))
printf("Error occurred at: %s, in %s at %i",  #v, __FILE__, __LINE__);
;
return 0;
}

as you can see here that extra ; in macro will create one empty statement. but it will not create problem in such condition but
Case 2:if you are using that macro with any if statement

int main()
{
if(1)
  Assert(0);
else 
  printf("ShareProgrammingTips");
return 0;
}

this will expand as

int main()
{
if(1)
  if(!(v)) 
     printf("Error occurred at: %s, in %s at %i",  #v, __FILE__, __LINE__);
  ;               //this empty statement will close if block and create error for below else block        
else 
  printf("ShareProgrammingTips");
return 0;
}

here that extra statement will close if block and create error for below else block. and this code will not even compile.

if you have encapsulated your macro then that will be expand as

int main()
{
if(1)
  if(!(v))
   do {
     printf("Error occurred at: %s, in %s at %i",  #v, __FILE__, __LINE__);
   } while(0);                   
else 
  printf("ShareProgrammingTips");
return 0;
}

Here it will be not create any problem for complication.
If your macro have multi statement then in that case also it will help you to over come from such condition.
with such encapsulataion method you can use macro as just calling any function must be followed by ;

 

JIGAR PATEL

hey I am an Artist who love to write code…! Well I am an EC graduate From Ganpat University and now i am working as Embedded software engineer in one private firm.. find me at here JigAr Patel

More PostsWebsiteTwitterFacebook

You may like to read this also....

Post comment

*

Follow us on Twitter! Follow us on Twitter!

Search in this website

our sponsors

latest comments

Find us on Facebook

Top Authors

36 posts
saurabh
22 posts
10 posts

Find us on stackoverflow

Polls

Tell us who you are

View Results

Loading ... Loading ...

My Bookmarks

Sponsers Link