C语言-函数-#define

本文深入探讨了C语言中预处理器指令#define的功能和用法,包括宏定义的基本语法、带参数宏的创建以及如何使用复杂宏避免代码污染。通过实例展示了#define在创建伪函数、条件判断和循环结构中的应用。

#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 );
 }

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值