c++宏定义命令
时间: 2023-08-11 17:11:13 浏览: 50
宏定义是C++预处理器提供的一种功能,可以将一些常量或代码片段定义为一个标识符,从而方便地在程序中使用。
下面是一些常用的宏定义命令:
1. #define:定义宏
语法: #define 宏名 值
示例:
```
#define PI 3.1415926
#define MAX(a, b) ((a) > (b) ? (a) : (b))
```
2. #undef:取消已定义的宏
语法: #undef 宏名
示例:
```
#undef PI
```
3. #ifdef:判断宏是否已定义
语法: #ifdef 宏名
示例:
```
#ifdef PI
cout << "PI has been defined" << endl;
#endif
```
4. #ifndef:判断宏是否未定义
语法: #ifndef 宏名
示例:
```
#ifndef PI
cout << "PI has not been defined" << endl;
#endif
```
5. #if:条件编译
语法: #if 常量表达式
示例:
```
#if PI > 3
cout << "PI is greater than 3" << endl;
#endif
```
6. #else:与#if连用,表示条件不成立时执行的代码
语法: #else
示例:
```
#if PI > 3
cout << "PI is greater than 3" << endl;
#else
cout << "PI is less than or equal to 3" << endl;
#endif
```
7. #elif:与#if连用,表示多个条件分支
语法: #elif 常量表达式
示例:
```
#if PI > 3
cout << "PI is greater than 3" << endl;
#elif PI < 3
cout << "PI is less than 3" << endl;
#else
cout << "PI is equal to 3" << endl;
#endif
```
注意:所有的宏定义命令都必须写在文件的开头或在#include之前,否则会报错。