#define FREE1(x) do { free(x); x = NULL; } while (0);
#define FREE2(x) { free(x); x = NULL; }
What is the difference between these macros?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your question is about the
do/whiletrick in macros, there’s no difference, because you apparently made an error in the first macro definition, which completely defeated the purpose of the trick. You put the;after thewhole (0). The proper implementation should absolutely not have the;after thewhile (0)in the first macro. This is the whole point of thedo/whiletrick.Now this code will not compile
This code will not compile either
The point of the
do/whiletechnique is to make this code compile. But it will not compile with yourFREE1macro either because of the aforementioned error.However, if you define the first macro correctly
then the first macro will work perfectly fine in the above code samples. This is actually the reason people use the
do/whiletechnique in multi-statement macros – to make it work correctly and uniformly with ordinary functions in such contexts.P.S. As a side note, the purpose of all such techniques is to turn a group of multiple statements into one compound statement. In your specific case the
free(x); x = NULL;sequence can be re-implemented as a single expression(free(x), x = NULL), which eliminates the need for any multi-statement macro techniques, i.e. thiswill work as well. But it is a matter of personal preference.