I am thinking about the right side (expansion) of a function like macro. Consider this example:
#define addOneTo(a) (a)++
Would do the job. But then I came across to a compound statements to be expressed via macros like this one:
#define addOneTo(a,b) (a)++; (b)++
Will do the job too. But if I want to use the macro in this occasion:
if(true)
addOneTo(a,b);
I would get:
if(true)
(a)++; (b)++;
In ^^this^^ case b
will be incremented no-matter the value of the expression in the if
statement. And this is not what I want. Therefore I googled it, and came across to this solution:
#define addOneTo(a,b) do{ (a)++; (b)++; }while(0)
So I am happy with the example ^^above^^, except I don't understand the do while(0)
, cant we just use compound statement like this???:
#define addOneTo(a,b) { (a)++; (b)++; }
What is the motivation behind this implementation?