Saturday, April 6, 2013

C C++ Interview Question. Question 1

When should you use "do while" in C macro ?
 
One cool thing I learned about C macro on Quora was about using
do while
in macro which are multiple statement.

for example if we have this macro:

1
2
3
#define macro1 line1;\
line 2;\
line3;


if we use this macro in our code like this:

1
2
if (condition)
macro1

then in that case
line2
and
line3
are executed always irrespective of
condition
, which was not the original intention.

so we should have the macro like this instead:

1
2
3
4
#define macro1 do { line1;\
line 2;\
line3;
 } while(0);

No comments:

Post a Comment