欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言-函数-#define

程序员文章站 2024-03-23 10:27:52
...

#define

Syntax:

#define macro-name replacement-string

The #define command is used to make substitutions throughout the file in which it is located. In other words, #define causes the compiler to go through the file, replacing every occurrence of macro-name with replacement-string. The replacement string stops at the end of the line.

Example code:

Here's a typical use for a #define (at least in C):

#define TRUE 1
   #define FALSE 0
   ...
   int done = 0;
   while( done != TRUE ) {
      ...
   }

Another feature of the #define command is that it can take arguments, making it rather useful as a pseudo-function creator. Consider the following code:

 #define absolute_value( x ) ( ((x) < 0) ? -(x) : (x) )
   ...
   int x = -1;
   while( absolute_value( x ) ) {
      ...
   }            

It's generally a good idea to use extra parentheses when using complex macros. Notice that in the above example, the variable "x" is always within it's own set of parentheses. This way, it will be evaluated in whole, before being compared to 0 or multiplied by -1. Also, the entire macro is surrounded by parentheses, to prevent it from being contaminated by other code. If you're not careful, you run the risk of having the compiler misinterpret your code.

Here is an example of how to use the #define command to create a general purpose incrementing for loop that prints out the integers 1 through 20:

 #define count_up( v, low, high ) /
   for( (v) = (low); (v) <= (high); (v)++ )          

 ...            

 int i;
 count_up( i, 1, 20 ) {
   printf( "i is %d/n", i );
 }

 

相关标签: c c语言