freeCodeCamp/guide/chinese/c/macros/index.md

1.3 KiB
Raw Blame History

title localeTitle
Macros in C C中的宏

C中的宏

宏是一段具有给定名称的代码。使用名称时,它将替换为宏的内容。

定义宏

#define关键字用于定义新宏。接下来是名称和内容。按照惯例,宏名称以大写字母书写。

#define PI 3.14 

如果你这样使用宏:

printf("Value of PI: %d", PI); 

写这个是一样的:

printf("Value of PI: %d", 3.14); 

宏的类型

有两种类型的宏。上面显示Object-like宏和Function-like宏。

功能类宏

类似函数使用相同的#define关键字。区别在于您在函数名后使用了一对括号。

#define hello_world() printf("Hello World!") 

所以打电话:

hello_world() 

你得到:

printf("Hello World!"); 

您也可以设置参数:

#define hello(X) printf("Hello " X "!") 

现在打电话:

hello("World"); 

你得到了相同的:

printf("Hello World!"); 

更多信息:

GCC在线文档

GCC在线文档类似对象的宏

GCC在线文档类似函数的宏