Do {} while (0) can be seen in both the Linux kernel and other famous C and C ++ libraries) Such Writing seems meaningless. In fact, it comes from famous masters and is used in macro definition. Previously, I learned that using the semicolon after macro-defined functions in a program may easily lead to problems. Today, I am deeply aware of it. First look at a simple macro # Define safe_free (p) do {free (p); P = NULL;} while (0) If do... while (0) is removed) That is, safe_free (P) is defined # Define safe_free (p) Free (p); P = NULL; The following code If (null! = P) Safe_free (P) Else // Do something Will be expanded: If (null! = P) Free (p); P = NULL; Else // Do something As a result, if has two statements, the second statement will always be executed, and else will no longer match the original if statement. Therefore, when defining macro functions, smart people usually add {} # Define safe_free (p) {free (p); P = NULL ;} This seems to have solved the problem, but there are still potential risks. Because many people are used to adding C code at the end; People without experience often add the safe_free (p) directly to the backend regardless of whether the safe_free (P) is in uppercase; For example If (null! = P) Safe_free (P ); Else // Do something Expanded If (null! = P) {Free (p); P = NULL ;}; Else // Do something This still causes if and else matching to be damaged. If you use the famous Method # Define safe_free (p) do {free (p); P = NULL;} while (0) So If (null! = P) Safe_free (P ); Else // Do something Expand If (null! = P) Do {Free (p); P = NULL ;} While (0 ); Else // Do something Okay, it's okay. This is what the book says, but I think # Define safe_free (p) do {free (p); P = NULL ;}while (0) However, if the user suddenly realizes that safe_free (P) is a macro, he cannot add it after safe_free (P; For example If (null! = P) Safe_free (P) Else // Do something Expand If (null! = P) Do {Free (p); P = NULL ;}; While (0) Else // Do something In this case, while (0) is not followed; an error is still reported! It's just because it's not smart enough. The easiest way to solve the problem is to have good programming habits. An if else structure without any problems can solve all the problems. If (null! = P) {// Do something} Else {// Do something} It is two points, null! = P instead of P! = NULL, there is a complete {} match It is easy to say, but it is still difficult for us to see perfect writing on the Internet or even famous books. Do not be lazy. Try a few more than {}; otherwise, the price will be more painful. |