C - macros use technique - do while(0);

it is not common when you see a lot of C language has something similar to the following defintion. 

 

 

#define macro_name(arg) do  { \
  // ... \
} while (0);

 

but why do we have this touble, why to guard against some innocent piece of code with the nugatory/inconsequential code as above?

 

let's see some example.  first  I defined several macros. 

 

/**
* file: macros.cpp
* description: demonstrate how to use macros, and some of the techniques. 
*/

#define hash(x) do { \
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; \
} while (0);


#define hash2(x) {\
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; \
}

#define hash3(x) \
	int y = 0; \
	if ((x) > 0) y = ((x) << 1) + 1; \
	else y = ((-x) << 1) + 1; \
	y; 

 

and the code to test it. 

 

	// so apparantly you cannot use the macro in some if/while condition statement.
	//if (hash(1) != 3) { 
	//	cout << "hash macros works" << endl;	
	//}

	// but this is ok , you can treat the hash(i) as a single line of function. 
	for (int i = 0; i < 10; i ++) hash(i);

	// this is also OK, because there is a local scope indicator, but that should only work in C++, because C does not have local scope inside a local function?
	for (int i = 0; i < 10; i ++) hash2(i);

	// this is NOT ok,  when the code is expanded, you will see errors
	//for (int i = 0; i < 10; i++) hash3(i);

 

as you cna see, that with the necessary do while statement, and with the help from compiler (because it can optimize the hopeless do while (0); and run the code within only once), you can treat the macros defined as a single line code - many expect it to be. 

你可能感兴趣的:(c)