macro definitions (#define, #undef)

本文介绍C++中使用预处理器指令#define定义宏的方法,包括常量宏定义及带参数的函数宏定义。此外还介绍了如何使用#undef取消宏定义,以及宏定义中特殊操作符#和##的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

macro definitions (#define, #undef)

To define preprocessor macros we can use  #define . Its format is:

#define identifier replacement

When the preprocessor encounters this directive, it replaces any occurrence of  identifier  in the rest of the code by replacement . This  replacement  can be an expression, a statement, a block or simply anything. The preprocessor does not understand C++, it simply replaces any occurrence of  identifier  by  replacement .

1
2
3
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
int table2[TABLE_SIZE]; 


After the preprocessor has replaced  TABLE_SIZE , the code becomes equivalent to:

1
2
int table1[100];
int table2[100]; 


This use of #define as constant definer is already known by us from previous tutorials, but  #define  can work also with parameters to define function macros:

 
#define getmax(a,b) a>b?a:b 


This would replace any occurrence of  getmax  followed by two arguments by the replacement expression, but also replacing each argument by its identifier, exactly as you would expect if it was a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// function macro
#include <iostream>
using namespace std;

#define getmax(a,b) ((a)>(b)?(a):(b))

int main()
{
  int x=5, y;
  y= getmax(x,2);
  cout << y << endl;
  cout << getmax(7,x) << endl;
  return 0;
}
5
7


Defined macros are not affected by block structure. A macro lasts until it is undefined with the #undef preprocessor directive:

1
2
3
4
5
#define TABLE_SIZE 100
int table1[TABLE_SIZE];
#undef TABLE_SIZE
#define TABLE_SIZE 200
int table2[TABLE_SIZE];


This would generate the same code as:

1
2
int table1[100];
int table2[200];


Function macro definitions accept two special operators (# and ##) in the replacement sequence:
If the operator  #  is used before a parameter is used in the replacement sequence, that parameter is replaced by a string literal (as if it were enclosed between double quotes)

1
2
#define str(x) #x
cout << str(test);


This would be translated into:

 
cout << "test";


The operator  ##  concatenates two arguments leaving no blank spaces between them:

1
2
#define glue(a,b) a ## b
glue(c,out) << "test";


This would also be translated into:

 
cout << "test";


Because preprocessor replacements happen before any C++ syntax check, macro definitions can be a tricky feature, but be careful: code that relies heavily on complicated macros may seem obscure to other programmers, since the syntax they expect is on many occasions different from the regular expressions programmers expect in C++.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值