Why does while (0) wonderful? Because it's really good, and it's pretty good to implement in the Linux kernel, let's look at the relevant code in the kernel:
#define DB_ERROR (FMT, ...) do { fprintf (stderr, "(Error):"); fprintf (stderr, FMT, # #__VA_ARGS__); } while (0)
This is just a normal output of debugging information, some people will think, you this is not superfluous it? Is it possible to remove the does while (0)? In fact, let's take a look at the example, though it's simple:
int main (void) {while (0) { printf ("Hello world\n");} do{printf ("Hello world1\n");} while (0); return 0; }
This is a simple code that can no longer be simple, but still to mention, see the results of the operation:
Everyone knows that the first while (0) is definitely not running, because the value in the while () bracket is equal to 0 and the logic is false, that is, the Hello World in the code block does not run, but does while (0) is different, and does while (0) even if the condition is not true, Will fight to do it once!
That is, why does the kernel code do this because the kernel code uses do{}while (0), which is guaranteed to execute correctly wherever it is, which is the best place to use it, or sometimes when the program is debugged, The debug statement alone is not printing is actually very normal things, do not know when you write code when you have encountered, anyway, I have met, and then is to use such a method to locate the wrong point, smooth correction.
The code is simple, but with good use of fine proficiency is not always able to get what you want, the more simple things, sometimes, the applicable value is very nice!
Share the following debug output program I implemented, can be used later when the template developed:
#include <stdio.h> #include the <stdarg.h>//core code is do{}while (0), which guarantees that the #define can be executed correctly anywhere, Db_error ( FMT, ...) do { fprintf (stderr, "(Error):"); fprintf (stderr, FMT, # #__VA_ARGS__); } while (0) #define DB_MSG (FMT, ...) do { fprintf (stdout, "(msg):"); fprintf (stdout, FMT, # #__VA_ARGS__); } while (0) #define Db_warn (FMT, ...) Do {fprintf (stdout, "(warn):"); fprintf (stdout, FMT, # #__VA_ARGS__); } while (0) #define DB_DEBUG (FMT, ...) do { fprintf (stdout, "(Debug):"); fprintf (stdout, FMT, # #__VA_ARGS__); } while (0) int main (void) {Db_error ("h\n");d B_warn ("e\n");d b_debug ("llo\n"); return 0;}
Operation Result:
Debug information before, quickly know where to print the statement, convenient debug! Quickly locate the bug in the program!
C language in the Linux kernel does while (0) magical method